﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using LPV_POS.Module;
using DevExpress.XtraEditors;
using DevExpress.XtraRichTextEdit.API.Native;
using DevExpress.XtraRichTextEdit.Model;
using System.Reflection;
using System.Linq;
//using DevExpress.XtraRichEdit.Commands;
//using DevExpress.XtraRichEdit.Commands.Internal;
using DevExpress.XtraBars.Commands.Internal;
using System.Runtime.InteropServices;
using System.Runtime;
using Microsoft.Win32;
using LPV_POS.In;
using LPV_POS.mh_pos.mh_ban_hang;
using LPV_POS.mh_pos.mh_inbaocao;
using LPV_POS.Baocao;
//using DevExpress.XtraRichEdit;

namespace LPV_POS.mh_pos
{
    public partial class mh_banhang_CT_Sua : DevExpress.XtraEditors.XtraForm
    {
        public mh_banhang_CT_Sua(string sTenCongTy, string sCaLamViec, Boolean _iorder_Cho_Khach_Dat_Ban)
        {
            InitializeComponent();
            lblcalamviec.Text = sCaLamViec;
            lbel_tencongty.Text = sTenCongTy;
            iorder_Cho_Khach_Dat_Ban = _iorder_Cho_Khach_Dat_Ban;

        }

        #region "   Property"
        private float sl_giamgia = 1;
        Boolean iorder_Cho_Khach_Dat_Ban = false;
        int iHINH_THUC_BAN_HANG = 0;
        //public Boolean bDaVaoCa = false;
        private Boolean bLoadform = false;
        private System.Windows.Forms.Control Control_Current = null;
        private System.Windows.Forms.Control Panel_Current = null;
        DataTable tbBH_PHIEU_TMP = null;
        DataTable tbBH_PHIEU_CT_TMP = null;
        DataRow drBH_PHIEU_CT_TMP = null;
        public DataTable tbDM_LOAIDICHVU = null;
        DataTable tbDeletePhieuCT = null;

        public string sBAN_MA = "";
        public string sPhieu_Ma = null;
        public string sKhuVucMa = "";
        public string sMaThe_VIP = "";
        //public string sMaThe_VIP_TenKhachHang = "";

        int ihandle = 0;
        //Boolean iPhieuMoi = false;
        Boolean iCoVAT = false;//20101002


        Color cMauNen_lblMenhGia_ThanhToan;
        Color cMauNen_lblChinhSua;
        Color cMauNen_lblGiamGia;
        chon ochon = new chon();
        Boolean iLoad_TienTip = false;
        Boolean iLoad_VAT = false;
        enum chon
        {
            None,
            ChinhSuaHH,
            MenhGia,
            GiaBan         //giá bán
        }
        enum giamgia_theVIP
        {
            None,
            hoadon_tien,
            hoadon_phantram//,
            //mon_renhat_tien,
            //mon_renhat_phantram,
            //mon_cuoicung_tien,
            //mon_cuoicung_phantram
        }
        giamgia_theVIP ogiamgia_theVIP = giamgia_theVIP.None;
        #endregion

        #region "   mh_banhang_Load"
        private void mh_banhang_Load(object sender, EventArgs e)
        {
            col_SO_LUONG.DisplayFormat.FormatString = "N" + Variable.tbBH_CAU_HINH.Rows[0]["SO_THAP_PHAN"];
            this.Load_BanHang();
            cMauNen_lblChinhSua = lblChinhSua.BackColor;
            cMauNen_lblMenhGia_ThanhToan = lblMenhGia_ThanhToan.BackColor;
            cMauNen_lblGiamGia = lblGiaBan.BackColor;
            //-== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== 


            this.Show_Apply_VAT();
            //
            lblxoa_ThucDon.Text = "Xóa\nThực Đơn";
            lblHuy_HoaDon.Text = "Hủy\nHóa Đơn";
            //lblPHU_THU_KHAC.Text = "Tính\nTiền Giờ";
            lblInLai_HoaDon.Text = "In Lại\nHóa Đơn";
            //

            timer1.Enabled = false;
            DateTime ngayHeThong = this.f_ngayhienhanh();
            if (ngayHeThong.Year != 1900)
                timer1.Tag = ngayHeThong;
            this.ShowData_Grd();
            this.ShowInfo();
            if (tbBH_PHIEU_CT_TMP.Rows.Count == 0)
            {
                lblCTHD_VAT.Text = "";
                lblCTHD_VAT1.Text = "";
                lblCTHD_VAT1.Visible = false;
            }

            bLoadform = true;
            //            
            timer1.Enabled = true;
            tbBH_PHIEU_CT_TMP.AcceptChanges();
            tbBH_PHIEU_TMP.AcceptChanges();
            //
            cpublic ocpublic = new cpublic();

            string sReceipt_On = ocpublic.Registry_Get(this.Name + lblReceipt_On.Name) + "";
            string sBill_On = ocpublic.Registry_Get(this.Name + lblBill_On.Name) + "";

            if (sReceipt_On != "")
                lblReceipt_On.Text = sReceipt_On;
            else
                lblReceipt_On_Click(null, null);

            if (sBill_On != "")
                lblBill_On.Text = sBill_On;
            else
                lblBill_On_Click(null, null);

            //load Registry
            int iHandle = this.Load_NhomMon_Default();
            if (iHandle >= 0 && gvNhom_Mon.FocusedRowHandle != iHandle)
            {
                gvNhom_Mon.FocusedRowHandle = iHandle;
                gvNhom_Mon.SelectRow(iHandle);
            }
            else if (iHandle >= 0 && gvNhom_Mon.FocusedRowHandle == iHandle)
            {
                gvNhom_Mon.FocusedRowHandle = iHandle;
                gvNhom_Mon.SelectRow(iHandle);
                this.gvNhom_Mon_FocusedRowChanged(null, null);
            }
            else
                this.gvNhom_Mon_FocusedRowChanged(null, null);


            //-------------------------- show scroll panel -----------------------------
            //     this.panel1.VisibleAutoScrollVertical 
            //pnlSoDo_MonAn

            //-----------------------------------------------------------------------------

            int.TryParse(Variable.tbBH_CAU_HINH.Rows[0]["HINH_THUC_BAN_HANG_combo"] + "", out iHINH_THUC_BAN_HANG);


            lblTamTinh.Enabled = iHINH_THUC_BAN_HANG != 0;
            ///lblTamTinh.Text //
            Boolean bCO_TINH_TIENGIO = false;
            Boolean.TryParse(tbDM_LOAIDICHVU.Rows[0]["CO_TINH_TIENGIO"] + "", out bCO_TINH_TIENGIO);
            if (!bCO_TINH_TIENGIO)
                lblTamTinh.Text = "";
            if (tbDM_LOAIDICHVU.Rows[0]["OBJID"] + "" == "2")//hOTEL
            {

                if (sMaThe_VIP == "" || sMaThe_VIP == "0" || sMaThe_VIP == "-1")
                {
                    mh_dmkhachhang omh_dmkhachhang = new mh_dmkhachhang();
                    DataRow dr = omh_dmkhachhang.ShowForm_fromBanHang(lblKhuVuc_Ban.Tag + "");

                    if ((omh_dmkhachhang.DialogResult != DialogResult.OK) || dr == null)
                    {
                        this.Dispose();
                        //sMaThe_VIP = "";
                        //return;
                    }
                    sMaThe_VIP = dr["THEKHACHHANG"] + "";
                    tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] = sMaThe_VIP;
                }

                //Set Default o theo ngay
                if (tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] + "" == "")//moi vao thi tinh tien theo ngay
                    tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] = 1;
                else if (tbBH_PHIEU_CT_TMP.Rows.Count == 0)
                    tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] = 1;
                else if (tbBH_PHIEU_CT_TMP.Rows.Count == 1 && tbBH_PHIEU_CT_TMP.Rows[0]["OBJID"] + "" == "")
                    tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] = 1;

                this.HienThi_oTheoNGay_Gio();

                //this.Tinh_Tien_Gio_Click();
            }

        }
        #endregion

        #region "   Load_NhomMon_Default"
        int Load_NhomMon_Default()
        {
            string sNhom_Mon_ma = new cpublic().Registry_Get(this.Name + gvNhom_Mon.Name) + "";

            DataTable tbDM_NHOMHH = (DataTable)grdDM_NHOMHH.DataSource;
            if (sNhom_Mon_ma != "")
            {
                int iHandle = -1;
                for (iHandle = 0; iHandle < tbDM_NHOMHH.Rows.Count; iHandle++)
                    if (tbDM_NHOMHH.Rows[iHandle]["OBJID"] + "" == sNhom_Mon_ma)
                        return iHandle;
            }
            return -1;
        }
        #endregion

        #region"    ShowInfo()"
        void ShowInfo()
        {
            thuvien othuvien = new thuvien();
            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= 
            ////////////////////////    tbBH_PHIEU_TMP  /////////////////////////////////////
            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= 
            tbBH_PHIEU_TMP = othuvien.SP_SelectDataTable("sp_mh_banhang_sua",
                                                        new string[] { "@flag", "@DM_BAN_MA", "@BH_PHIEU_MA", "@iorder_Cho_Khach_Dat_Ban" },
                                                        new object[] { 4, sBAN_MA, sPhieu_Ma, iorder_Cho_Khach_Dat_Ban });
            tbBH_PHIEU_TMP.TableName = "BH_PHIEU_TMP";
            

            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= 
            ////////////////////////    tbBH_PHIEU_CT_TMP   /////////////////////////////////
            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= 
            string sMaPhieu = "";
            if (tbBH_PHIEU_TMP.Rows.Count > 0)
            {
                sMaPhieu = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
                if (sMaThe_VIP == "")
                    sMaThe_VIP = tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] + "";// ma the khach hang luu vao "BH_PHIEU_TMP.CUSTOMER_ID"
            }

            //else
            //    iPhieuMoi = true;
            tbBH_PHIEU_CT_TMP = othuvien.SP_SelectDataTable("sp_mh_banhang_sua",
                                                        new string[] { "@flag", "@BH_PHIEU_MA" },
                                                        new object[] { 5, sMaPhieu });
            tbDeletePhieuCT = tbBH_PHIEU_CT_TMP.Clone();


            //this.Load_TenKhachHangVIP();

            tbBH_PHIEU_CT_TMP.TableName = "BH_PHIEU_CT_TMP";
            this.ShowInfo_Config();

            ///////////////////////////////////////////////////////tbDM_LOAIDICHVU
            string sSQL = "SELECT a.* " +
                    "FROM DM_LOAIDICHVU a " +
                    "   INNER JOIN DM_BAN b ON a.OBJID = b.DM_LOAIDICHVU_MA " +
                    "                           AND B.OBJID = '" + sBAN_MA + "'";
            tbDM_LOAIDICHVU = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sql" }, new object[] { sSQL });
            if (tbDM_LOAIDICHVU.Rows.Count > 0)
            {
                lblLoaiDichVu.Text = tbDM_LOAIDICHVU.Rows[0]["OBJNAME"] + "\n" + lblKhuVuc_Ban.Tag;
                lblLoaiDichVu.Tag = tbDM_LOAIDICHVU.Rows[0]["OBJNAME"] + "";

                if (tbDM_LOAIDICHVU.Rows[0]["CO_TINHGIO_THEONGAY"] + "" != "True")
                    lblCoTinhGio_TheoNgay.Text = "";

                //if (tbDM_LOAIDICHVU.Rows[0]["CAT_THOIGIAN"] + "" != "True")
                //    lblCatCo.Text = "";//20110402_bo

                //if (tbDM_LOAIDICHVU.Rows[0]["CO_TINH_TIENGIO"] + "" == "True")
                //{
                //    //if (tbBH_PHIEU_CT_TMP.Select("MaHH LIKE 'Tien_Gio'").Length == 0)
                //        this.Tinh_Tien_Gio_Click();

                //}


            }
        }

        //void Load_TenKhachHangVIP()
        //{
        //    if (sMaThe_VIP != "")
        //    {
        //        lblKhuVuc_Ban.Text = lblKhuVuc_Ban.Tag + "";// +"(" + sMaThe_VIP + ")";

        //        string sSQL = "SELECT ten = ISNULL(k.OBJNAME, nk.OBJNAME) " +
        //                      "FROM DM_THE t " +
        //                      "     LEFT JOIN DM_KHACHHANG k ON k.OBJID = t.DM_KHACHHANG_MA " +
        //                      "     LEFT JOIN DM_NHOMKHACHHANG nk ON t.DM_NHOMKHACHHANG_MA = nk.OBJID " +
        //                      "WHERE T.CODE LIKE '" + sMaThe_VIP + "' ";
        //        DataTable tbDM_THE = new thuvien().SP_SelectDataTable("SP_EXECUTESQL",
        //                                                            new string[] { "@sSQL" },
        //                                                            new string[] { sSQL });
        //        if (tbDM_THE.Rows.Count > 0)
        //        {
        //            lblKhuVuc_Ban.Text = lblKhuVuc_Ban.Text + "(" + tbDM_THE.Rows[0]["ten"] + ")";
        //            //sMaThe_VIP_TenKhachHang = tbDM_THE.Rows[0]["ten"] + "";
        //        }
        //    }
        //}

        void ShowInfo_Config()
        {

            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= 
            ////////////////////////    tbBH_PHIEU_TMP  /////////////////////////////////////
            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----=             
            tbBH_PHIEU_TMP.Columns["TIEN_GIO"].DefaultValue = 0;
            tbBH_PHIEU_TMP.Columns["THANH_TIEN"].DefaultValue = 0;
            tbBH_PHIEU_TMP.Columns["CK_PHANTRAM"].DefaultValue = 0;
            tbBH_PHIEU_TMP.Columns["CK_TIEN"].DefaultValue = 0;
            tbBH_PHIEU_TMP.Columns["VAT_PHANTRAM"].DefaultValue = 0;
            tbBH_PHIEU_TMP.Columns["VAT_TIEN"].DefaultValue = 0;
            tbBH_PHIEU_TMP.Columns["TTIEP_PHANTRAM"].DefaultValue = 0;
            tbBH_PHIEU_TMP.Columns["TTIEP_TIEN"].DefaultValue = 0;

            tbBH_PHIEU_TMP.Columns["PHU_THU_PHANTRAM"].DefaultValue = 0;//BS
            tbBH_PHIEU_TMP.Columns["PHU_THU"].DefaultValue = 0;//phí dịch vụ
            tbBH_PHIEU_TMP.Columns["PHU_THU_KHAC"].DefaultValue = 0;//phí dịch vụ
            if (tbBH_PHIEU_TMP.Rows.Count == 0)
            {
                tbBH_PHIEU_TMP.Rows.Add(tbBH_PHIEU_TMP.NewRow());

                tbBH_PHIEU_TMP.Rows[0]["DM_BAN_MA"] = sBAN_MA;
                tbBH_PHIEU_TMP.Rows[0]["MAKHOHANG"] = Variable.ma_khohang;

                if (timer1.Tag + "" != "")
                    tbBH_PHIEU_TMP.Rows[0]["NGAY_GIO_VAO"] = timer1.Tag;
            }

            tbBH_PHIEU_TMP.Columns["DAT_COC"].DefaultValue = 0;
            if (tbBH_PHIEU_TMP.Rows[0]["DAT_COC"] + "" == "")
                tbBH_PHIEU_TMP.Rows[0]["DAT_COC"] = 0;

            if (tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] + "" == "")
                tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] = 0;

            if (tbBH_PHIEU_TMP.Rows[0]["PHU_THU_KHAC"] + "" == "")
                tbBH_PHIEU_TMP.Rows[0]["PHU_THU_KHAC"] = 0;

            //tbBH_PHIEU_TMP.Columns["TONG_TIEN"].Expression = "TIEN_GIO + THANH_TIEN - CK_TIEN - KM_TIEN + VAT_TIEN + TTIEP_TIEN - DAT_COC + PHU_THU + PHU_THU_KHAC";//CO CA CONG THUC TRONG sql (sp_mh_banhang_sua : @flag = 16)
            tbBH_PHIEU_TMP.Columns["TONG_TIEN"].Expression = "TIEN_GIO + THANH_TIEN - CK_TIEN - KM_TIEN + VAT_TIEN + TTIEP_TIEN + PHU_THU + PHU_THU_KHAC";//CO CA CONG THUC TRONG sql (sp_mh_banhang_sua : @flag = 16)

            // lblHD_TongTien.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"].ToString()).ToString("N0");

            lblHD_CK1.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"].ToString()).ToString("N0");

            lblHD_PhiDichVu.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["PHU_THU"].ToString()).ToString("N0");

            lblHD_Phu_Thu_Khac.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["PHU_THU_KHAC"].ToString()).ToString("N0");

            lblHD_TIENTIEP1.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"].ToString()).ToString("N0");

            lblHD_VAT1.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["VAT_TIEN"].ToString()).ToString("N0");
            //
            #region "   grdHD tmp bo"
            //DataTable tbHD = new DataTable("HD");
            //tbHD.Columns.Add("c1",typeof(string));
            //tbHD.Columns.Add("c2", typeof(int));
            //tbHD.Columns.Add("c3", typeof(string));
            //tbHD.Columns.Add("c4", typeof(int));
            //DataRow dr1 = tbHD.NewRow();
            //dr1["c1"] = "CK";
            //dr1["c2"] = int.Parse(tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"].ToString());
            //dr1["c3"] = "TIỀN TIP";
            //dr1["c4"] = int.Parse(tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"].ToString());
            //tbHD.Rows.Add(dr1);
            //DataRow dr2 = tbHD.NewRow();
            //dr2["c1"] = "Vat";
            //dr2["c2"] = int.Parse(tbBH_PHIEU_TMP.Rows[0]["VAT_TIEN"].ToString());
            //dr2["c3"] = "PHỤ THU";
            //dr2["c4"] = int.Parse(tbBH_PHIEU_TMP.Rows[0]["PHU_THU"].ToString());
            //tbHD.Rows.Add(dr2);
            //grdHD.DataSource = tbHD;
            #endregion

            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= 
            ////////////////////////    tbBH_PHIEU_CT_TMP   /////////////////////////////////
            //----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----= ----=            
            tbBH_PHIEU_CT_TMP.Columns["CHIETKHAU_PHANTRAM"].DefaultValue = 0;
            tbBH_PHIEU_CT_TMP.Columns["CHIETKHAU_TIEN"].DefaultValue = 0;
            tbBH_PHIEU_CT_TMP.Columns["VAT_PHANTRAM"].DefaultValue = 0;
            tbBH_PHIEU_CT_TMP.Columns["VAT_TIEN"].DefaultValue = 0;
            tbBH_PHIEU_CT_TMP.Columns["THANH_TIEN"].Expression = "SO_LUONG * DON_GIA - CHIETKHAU_TIEN";// - CHIETKHAU_TIEN + VAT_TIEN";
            tbBH_PHIEU_CT_TMP.Columns["GIA_BAN"].Expression = "DON_GIA";
            grdBH_PHIEU.DataSource = tbBH_PHIEU_CT_TMP;
            //


        }
        void Show_Apply_VAT()
        {
            string sVAT = new cpublic().Registry_Get("BH_PhuThu.VAT") + "";
            iCoVAT = sVAT == "1";//20101002
            if (iCoVAT)
                toolTip1.SetToolTip(lbPhuThu, "Có VAT");
            else
                toolTip1.SetToolTip(lbPhuThu, "Không có VAT");
        }
        #endregion

        #region "   f_ngayhienhanh"
        private DateTime f_ngayhienhanh()
        {
            try
            {
                DataTable tb = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { "SELECT GETDATE()" });

                return (DateTime)tb.Rows[0][0];
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            return new DateTime(0);
        }
        #endregion

        #region "   ShowData"
        void ShowData(string _sMA_NHOM_HH)
        {
            try
            {
                //xóa hết control nằm trong Panel "pnlSoDoBan"
                //pnlSoDo_MonAn.Controls.Clear();


                DataTable tbDM_HH = new thuvien().SP_SelectDataTable("sp_mh_banhang_sua",
                                                                    new string[] { "@MANHOMHH", "@flag", "@MAKHOHANG", "@thang_nam", "@DM_THE_CODE" },
                                                                    new object[] { _sMA_NHOM_HH, 3, Variable.ma_khohang, timer1.Tag, sMaThe_VIP });
                int xdong = 1, ycot = 1;
                cpublic ocpublic = new cpublic();
                Font _font = new Font("Times New Roman", 13, FontStyle.Bold, GraphicsUnit.Point);


                this.Reset_pnlSoDo_MonAn();//20101228
                Bitmap iHinh_nen = null;

                System.Windows.Forms.Control[] _Controls = new System.Windows.Forms.Control[tbDM_HH.Rows.Count];
                //int i = 0;
                foreach (DataRow dr in tbDM_HH.Rows)
                {
                    System.Windows.Forms.Control NewControl = this.getPanel(dr, xdong, ycot);
                    //NewControl.BackColor = System.Drawing.Color.Transparent;

                    int iii = NewControl.Text.Length;

                    if (NewControl.Text.Trim().Length > 50)
                        _font = new Font("Times New Roman", 8, FontStyle.Bold, GraphicsUnit.Point);
                    else if (NewControl.Text.Trim().Length > 40)
                        _font = new Font("Times New Roman", 9, FontStyle.Bold, GraphicsUnit.Point);
                    else if (NewControl.Text.Trim().Length > 35)
                        _font = new Font("Times New Roman", 11, FontStyle.Bold, GraphicsUnit.Point);
                    else
                        _font = new Font("Times New Roman", 11, FontStyle.Bold, GraphicsUnit.Point);

                    NewControl.Text = NewControl.Text + "";
                    if (iHinh_nen != null)
                    {
                        NewControl.BackgroundImage = (Image)(iHinh_nen.Clone());
                        //ocpublic.BoGoc_Control_KhongText(NewControl, Color.FromArgb(254, 255, 153), Color.Red, Color.Black, _font, true);
                    }
                    else
                        iHinh_nen = (Bitmap)ocpublic.BoGoc_Control_KhongText(NewControl, Color.FromArgb(254, 255, 153), Color.Red, Color.Black, _font, true).Clone();

                    NewControl.ForeColor = Color.Red;
                    NewControl.Font = _font;
                    ocpublic.SetImageText(NewControl);
                    //this.SetHinhAnh(NewControl, dr["HINH"]);

                    pnlSoDo_MonAn.Controls.Add(NewControl);
                    //_Controls[i++] = NewControl;
                    if (ycot == 4)
                    {
                        ycot = 1;
                        xdong += 1;
                    }
                    else
                        ycot += 1;
                }
                //this.Reset_pnlSoDo_MonAn();//20101228
                //for (int _i = 0; _i < i; _i++)
                //{
                //    pnlSoDo_MonAn.Controls.Add(_Controls[_i]);
                //}
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }

        }
        void SetHinhAnh(System.Windows.Forms.Control ctrl, Object _HinhAnh)
        {
            try
            {
                if (_HinhAnh + "" != "")
                    ctrl.BackgroundImage = new cpublic().ConvertByteArrayToImage(_HinhAnh);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion

        #region "   ShowData_Grd"
        void ShowData_Grd()
        {//OBJID
            thuvien othuvien = new thuvien();
            string sSQL = "";
            ////////////////
            //if (sPhieu_Ma + "" != "")
            //{
            //    sSQL = "SELECT bp.DM_BAN_MA FROM BH_PHIEU_TMP bp WHERE bp.OBJID LIKE '" + sPhieu_Ma + "'";
            //    DataTable tbMaBan = othuvien.SP_SelectDataTable("sp_executeSQL", new string[] { "@sSQL" }, new object[] { sSQL });
            //    if (tbMaBan.Rows.Count > 0)
            //        sBAN_MA = tbMaBan.Rows[0]["DM_BAN_MA"] + "";
            //}


            ///////////////////////////////////////////////////////tbDM_NHOMHH
            this.ShowDM_NHOMHH(ChonTrang.None);
            ///////////////////////////////////////////////////////tbKhuVuc_Ban
            sSQL = "SELECT ban = k.OBJNAME +' - '+ b.OBJNAME " +
                    "FROM DM_BAN b " +
                    "     LEFT JOIN DM_KHUVUC k ON k.OBJID = b.MAKHUVUC " +
                    "WHERE b.OBJID = '" + sBAN_MA + "'";
            DataTable tbKhuVuc_Ban = othuvien.SP_SelectDataTable("sp_executesql", new string[] { "@sql" }, new object[] { sSQL });
            //lblKhuVuc_Ban.Text = "";
            if (tbKhuVuc_Ban.Rows.Count > 0)
            {
                //lblKhuVuc_Ban.Text = tbKhuVuc_Ban.Rows[0]["ban"] + "";
                lblKhuVuc_Ban.Tag = tbKhuVuc_Ban.Rows[0]["ban"];
            }


        }
        #endregion

        #region "   Label_Click"
        void Label_Click(object sender, EventArgs e)
        {
            string str = "";
            try
            {
                Panel_Current = null;
                Control_Current = (System.Windows.Forms.Control)sender;

                //if (Control_Current.ToString().IndexOf("Panel") > 0)
                //    Panel_Current = Control_Current;
                //else if (Control_Current.Parent.ToString().IndexOf("Panel") > 0)
                //    Panel_Current = Control_Current.Parent;
                //else if (Control_Current.Parent.Parent.ToString().IndexOf("Panel") > 0)
                //    Panel_Current = Control_Current.Parent.Parent;


                str = Control_Current.Tag + "";
                string _sMA_HH = "";
                string _sTEN_HH = "";
                float _GIA = 0;
                string _sMa_DVT = "";
                int _khuyenMai_PhanTram = 0;
                string _DM_MAYIN_BEP_MA = "";
                object _ivat_phantram = null;
                object iBAN_GIA_MO = null;
                string _sDM_NHOMCHUHH_CODE = "";

                if (str.Split('#').Length > 1)
                {
                    _sMA_HH = str.Split('#')[0] + "";
                    _sTEN_HH = str.Split('#')[1] + "";
                    _GIA = float.Parse("0" + str.Split('#')[2]);
                    _sMa_DVT = str.Split('#')[3] + "";
                    int.TryParse(str.Split('#')[4] + "", out _khuyenMai_PhanTram);
                    _DM_MAYIN_BEP_MA = str.Split('#')[5] + "";
                    _ivat_phantram = str.Split('#')[6];
                    iBAN_GIA_MO = str.Split('#')[7];
                    _sDM_NHOMCHUHH_CODE = str.Split('#')[8];
                }

                //lblTon_Kho


                ///////////////////////////
                if (ochon == chon.ChinhSuaHH)
                {
                    mh_dm_HangHoa_chinhSua omh_dm_HangHoa_chinhSua = new mh_dm_HangHoa_chinhSua(_sMA_HH);
                    omh_dm_HangHoa_chinhSua.ShowDialog();
                    if (omh_dm_HangHoa_chinhSua.DialogResult == DialogResult.OK)
                    {
                        //this.gvNhom_Mon_FocusedRowChanged(null, null);
                        this.Load_TonKHO_1Mon(_sMA_HH);//20101214
                    }
                    ochon = chon.None;
                    return;
                }
                else if (ochon == chon.GiaBan)
                {
                    mh_banhang7_GiaBan omh_banhang7_GiaBan = new mh_banhang7_GiaBan(_sMA_HH);
                    float fGIA = omh_banhang7_GiaBan.ShowForm();
                    this.lblGiaBan_Click(null, null);
                    if (omh_banhang7_GiaBan.DialogResult == DialogResult.OK)
                        _GIA = fGIA;
                    else
                        return;
                }

                if (iBAN_GIA_MO + "" == "True" || _GIA == 0)
                {
                    _GIA = _GIA + 0;
                    mh_so_Ban_Gia_Mo omh_so = new mh_so_Ban_Gia_Mo("Giá mặt hàng (" + _sTEN_HH + ")", _GIA + "", "");
                    _GIA = int.Parse(omh_so.ShowForm() + "");
                    if (omh_so.DialogResult != DialogResult.OK)
                        return;

                }
                ///////////////////////////
                int isoluong = 1;
                if (new cpublic().IsNumeric(lblCTHD_ChietKhau.Text))
                    int.TryParse(lblCTHD_ChietKhau.Text, out isoluong);
                if (isoluong == 0)
                    isoluong = 1;
                this.gvHoaDon_CT_FocusedRowChanged(null, null);

                //NHOMCHUHH_CODE
                this.Insert2TableCT(_sDM_NHOMCHUHH_CODE, _sMA_HH, _sTEN_HH, _GIA, isoluong, _sMa_DVT, _khuyenMai_PhanTram, _DM_MAYIN_BEP_MA, _ivat_phantram);

                this.lblTongCong_Click(null, null);//20110308

            }
            catch (Exception ex)
            {
                string s = ex.Message;
                new mh_thongbao("Label_Click:\n" + ex.Message, 2).ShowDialog();
            }
        }
        void Insert2TableCT(string NHOMCHUHH_CODE, string _ma_HH, string _ten_HH, float _don_gia, int _SoLuong, string _sMa_DVT, int _khuyenMai_PhanTram, string _DM_MAYIN_BEP_MA, object _iVAT_PHANTRAM)
        {
            string sGOP_MON_CUNG_TEN_KHI_DAT_HANG = Variable.tbBH_CAU_HINH.Rows[0]["GOP_MON_CUNG_TEN_KHI_DAT_HANG"] + "";

            if (tbBH_PHIEU_CT_TMP.Select("MAHH='" + _ma_HH + "' AND (OBJID IS NULL OR OBJID = -1) AND DON_GIA = " + _don_gia).Length > 0 && sGOP_MON_CUNG_TEN_KHI_DAT_HANG == "True")
            {//da ton tai NEW_ROW                
                //
                for (ihandle = 0; ihandle < tbBH_PHIEU_CT_TMP.Rows.Count; ihandle++)
                    if ((tbBH_PHIEU_CT_TMP.Rows[ihandle]["OBJID"] + "" == "" || tbBH_PHIEU_CT_TMP.Rows[ihandle]["OBJID"] + "" == "-1") && tbBH_PHIEU_CT_TMP.Rows[ihandle]["MAHH"] + "" == _ma_HH)
                    {
                        int idongia_TMP = 0;
                        int.TryParse(tbBH_PHIEU_CT_TMP.Rows[ihandle]["DON_GIA"] + "", out idongia_TMP);
                        if (idongia_TMP == _don_gia)
                        {
                            this.SetSelectRow();
                            break;
                        }
                    }

                DataRow dr = tbBH_PHIEU_CT_TMP.Select("MAHH='" + _ma_HH + "' AND (OBJID IS NULL OR OBJID = -1)")[0];
                int isl = int.Parse("" + dr["SO_LUONG"]);
                _SoLuong = isl + _SoLuong;
                if (_SoLuong == 0)
                    this.lblxoa_ThucDon_Click(null, null);
                else
                    dr["SO_LUONG"] = _SoLuong;
            }
            else
            {//chua ton tai ==> NEW_ROW
                string color = "1";
                if (tbBH_PHIEU_CT_TMP.Rows.Count > 0)
                {
                    //color = tbBH_PHIEU_CT_TMP.Rows[tbBH_PHIEU_CT_TMP.Rows.Count - 1]["color"] + "";
                    //color = (color == "1" ? "0" : "1");
                    color = "2";
                }
                DataRow dr = tbBH_PHIEU_CT_TMP.NewRow();
                dr["OBJID"] = "-1";
                dr["MAHH"] = _ma_HH;
                dr["OBJNAME_HH"] = _ten_HH;
                dr["OBJNAME_HH_root"] = _ten_HH;
                dr["SO_LUONG"] = _SoLuong;
                dr["DON_GIA"] = _don_gia;
                dr["COLOR"] = int.Parse("0" + color);
                dr["DVT"] = _sMa_DVT;
                //dr["NGAY_TINH_GIO"] = 
                ////////////if (_khuyenMai_PhanTram > 999)
                ////////////{
                ////////////    dr["CHIETKHAU_PHANTRAM"] = 0;//CHIET_KHAU da dc tinh tai ham this.Tinh_Giam_Gia_THE_VIP()
                ////////////    dr["CHIETKHAU_TIEN"] = _khuyenMai_PhanTram;//
                ////////////}
                ////////////else
                ////////////{
                ////////////    dr["CHIETKHAU_PHANTRAM"] = _khuyenMai_PhanTram;//
                ////////////}
                dr["NHOMCHUHH_CODE"] = NHOMCHUHH_CODE;
                if (_DM_MAYIN_BEP_MA + "" != "")
                    dr["DM_MAYIN_BEP_MA"] = _DM_MAYIN_BEP_MA;

                dr["VAT_PHANTRAM"] = "0" + _iVAT_PHANTRAM;
                this.Refresh_VAT_CT(dr);
                tbBH_PHIEU_CT_TMP.Rows.Add(dr);
                this.gridView1_CellValueChanged(null, null);
                ihandle = tbBH_PHIEU_CT_TMP.Rows.Count - 1;

                this.SetSelectRow();

                grdBH_PHIEU.Refresh();
            }
            ogiamgia_theVIP = giamgia_theVIP.None;
            this.Tinh_Giam_Gia_THE_VIP();
            this.Update_SOLUONG_TMP(_ma_HH, _SoLuong, _don_gia, _sMa_DVT);//20101011
            this.RefreshCTHD(false);
            //this.TinhTongSUM();
        }
        #endregion

        #region "   Load_TonKHO_1Mon()"
        void Load_TonKHO_1Mon(string _sMaHH)
        {
            Font _font = new Font("Times New Roman", 13, FontStyle.Bold, GraphicsUnit.Point);
            DataRow dr = null;
            DataTable DM_HH = new thuvien().SP_SelectDataTable("sp_mh_banhang_sua",
                                                                    new string[] { "@flag", "@MAKHOHANG", "@thang_nam", "@DM_THE_CODE", "@OBJID" },
                                                                    new object[] { 20, Variable.ma_khohang, timer1.Tag, sMaThe_VIP, _sMaHH });
            if (DM_HH.Rows.Count > 0)
                dr = DM_HH.Rows[0];

            foreach (System.Windows.Forms.Control ctrl in pnlSoDo_MonAn.Controls)
            {
                if (ctrl.Name == "lblMonAn" + _sMaHH)
                {
                    System.Windows.Forms.Control NewControl = this.getPanel(dr, 1, 1);

                    if (NewControl.Text.Trim().Length > 35)
                        _font = new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point);
                    else
                        _font = new Font("Times New Roman", 11, FontStyle.Bold, GraphicsUnit.Point);
                    NewControl.Text = NewControl.Text + "";

                    NewControl.Location = ctrl.Location;

                    pnlSoDo_MonAn.Controls.Remove(ctrl);

                    new cpublic().BoGoc_Control(NewControl, Color.FromArgb(254, 255, 153), Color.Red, Color.Black, _font, true);
                    //this.SetHinhAnh(NewControl, dr["HINH"]);

                    pnlSoDo_MonAn.Controls.Add(NewControl);


                    return;
                }
            }
        }
        #endregion

        #region "   Update_SOLUONG_TMP"
        void Update_SOLUONG_TMP(string _maHH, float _soluong, float _DON_GIA, string _DVT)
        {
            thuvien othuvien = new thuvien();


            DataRow dr = tbBH_PHIEU_TMP.Rows[0];
            if (sPhieu_Ma + "" == "" || dr["MAKHOHANG"] + "" == "")
            {//neu co thay đổi dữ liệu thì --> luu
                string sGOP_MON_CUNG_TEN_KHI_DAT_HANG = Variable.tbBH_CAU_HINH.Rows[0]["GOP_MON_CUNG_TEN_KHI_DAT_HANG"] + "";
                if (sGOP_MON_CUNG_TEN_KHI_DAT_HANG == "True")
                    this.MergeDataRow();

                
                Boolean iReview = false;
            lannua:
                dr = tbBH_PHIEU_TMP.Rows[0];
                string[] param = new string[] { "@flag", "@OBJID", "@DM_BAN_MA", 
                                            "@NGUOI_LAP", "@CA",//"@NGAY_GIO_VAO", "@NGAY_GIO_RA", 
                                            "@TINH_TIEN_THEO_NGAY", "@TIEN_GIO", "@THANH_TIEN", 
                                            "@CK_PHANTRAM", "@CK_TIEN", 
                                            "@VAT_PHANTRAM", "@VAT_TIEN", 
                                            "@TTIEP_PHANTRAM", "@TTIEP_TIEN", 
                                            "@PHU_THU_PHANTRAM","@PHU_THU", "@PHU_THU_KHAC", 
                                            "@TONG_TIEN", "@GHI_CHU", "@MAKHOHANG",
                                            "@NGAY_LAM_VIEC","@KM_PHANTRAM","@KM_TIEN", "@DM_KHUYENMAI_MA",
                                            "@iorder_Cho_Khach_Dat_Ban"
                                            };
                Object[] val = new Object[] { 6, dr["OBJID"], sBAN_MA,
                                            Variable.username, "ca"+Variable.username,//Variable.calamviec,//20101201
                                            lblCoTinhGio_TheoNgay.Tag, dr["TIEN_GIO"], dr["THANH_TIEN"],
                                            dr["CK_PHANTRAM"], dr["CK_TIEN"], 
                                            dr["VAT_PHANTRAM"],dr["VAT_TIEN"],
                                            dr["TTIEP_PHANTRAM"],dr["TTIEP_TIEN"],
                                            dr["PHU_THU_PHANTRAM"],dr["PHU_THU"],dr["PHU_THU_KHAC"],
                                            dr["TONG_TIEN"],dr["GHI_CHU"], Variable.ma_khohang,
                                            Variable.ngay_lamviec,dr["KM_PHANTRAM"],dr["KM_TIEN"], dr["DM_KHUYENMAI_MA"],
                                            iorder_Cho_Khach_Dat_Ban
                                            };
                iReview = dr["OBJID"] + "" == "";
                //ko luu @MAKHOHANG
                sPhieu_Ma = othuvien.SP_Update("sp_mh_banhang_sua", param, val) + "";
                tbBH_PHIEU_TMP.Rows[0]["OBJID"] = sPhieu_Ma;

                if (iorder_Cho_Khach_Dat_Ban)
                    tbBH_PHIEU_TMP.Rows[0]["DAT_COC"] = this.GetDAT_COC(sPhieu_Ma);

                if (iReview)
                    goto lannua;
            }
            int ii = othuvien.SP_Update("sp_mh_banhang_sua", new string[] { "@flag", "@BH_PHIEU_MA" }, new string[] { "19", sPhieu_Ma });
            foreach (DataRow drCT in tbBH_PHIEU_CT_TMP.Rows)
            {
                ii = othuvien.SP_Update("sp_mh_banhang_sua",
                                                new string[] { "@flag", "@MAKHOHANG", "@MAHH", "@BH_PHIEU_MA", "@SO_LUONG", "@DON_GIA", "@DVT" },
                                                new object[] { 18, Variable.ma_khohang, drCT["MAHH"], sPhieu_Ma, drCT["SO_LUONG"], drCT["DON_GIA"], drCT["DVT"] });

            }
            this.TinhTongSUM();
            //this.gvNhom_Mon_FocusedRowChanged(null, null);
            this.Load_TonKHO_1Mon(_maHH);
        }
        #endregion

        #region "   lblTrangChu_Click"
        private void lblTrangChu_Click(object sender, EventArgs e)
        {
            //object o1OBJID = tbBH_PHIEU_TMP.Rows[0]["OBJID"];
            //if (tbBH_PHIEU_TMP.GetChanges() != null && o1OBJID + "" != "")
            //{
            //    if (iHINH_THUC_BAN_HANG == 1)
            //    {
            //        string s = "Dữ liệu đã có thay đổi.";
            //        DialogResult dlg = new mh_thongbao(s, 2).ShowForm();
            //        return;
            //    }

            //}
            this.DialogResult = DialogResult.Cancel;
            this.Dispose();
        }
        #endregion

        #region "   gvHoaDon_CT_FocusedRowChanged"
        private void gvHoaDon_CT_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {


            int iCK_TIEN = 0;
            int iVAT_TIEN = 0;
            Double dsoluong = 0;
            Double ddongia = 0;
            try
            {
                if (gvHoaDon_CT.GetSelectedRows().Length > 0)
                {
                    ihandle = gvHoaDon_CT.FocusedRowHandle;//20101013

                    int row = gvHoaDon_CT.GetSelectedRows()[0];//

                    for (int j = 0; j < gvHoaDon_CT.VisibleColumns.Count; j++)
                    {
                        drBH_PHIEU_CT_TMP = gvHoaDon_CT.GetDataRow(row);//

                        int.TryParse(drBH_PHIEU_CT_TMP["CHIETKHAU_TIEN"] + "", out iCK_TIEN);
                        int.TryParse(drBH_PHIEU_CT_TMP["VAT_TIEN"] + "", out iVAT_TIEN);

                        Double.TryParse(drBH_PHIEU_CT_TMP["SO_LUONG"] + "", out dsoluong);
                        Double.TryParse(drBH_PHIEU_CT_TMP["DON_GIA"] + "", out ddongia);

                        goto here;
                    }
                }
            here:
                lblCTHD_ChietKhau.Text = "CK THỰC ĐƠN";
                lblCTHD_ChietKhau1.Text = iCK_TIEN.ToString("N0");
                lblCTHD_ChietKhau1.Tag = dsoluong * ddongia + "";
                lblCTHD_ChietKhau1.Visible = true;

                lblCTHD_VAT.Text = "VAT THỰC ĐƠN";
                lblCTHD_VAT1.Text = iVAT_TIEN.ToString("N0");
                lblCTHD_VAT1.Visible = true;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion

        #region "   GetSelectedValues"
        private string GetSelectedValues(DevExpress.XtraGrid.Views.Grid.GridView view, string _tenCot)
        {
            if (view.SelectedRowsCount == 0) return "";

            // iterate cells and compose a tab delimited string of cell values
            for (int i = view.SelectedRowsCount - 1; i >= 0; i--)
            {
                int row = view.GetSelectedRows()[i];
                for (int j = 0; j < view.VisibleColumns.Count; j++)
                {
                    return view.GetDataRow(row)[_tenCot] + "";
                    //result += view.GetRowCellDisplayText(row, view.VisibleColumns[j]);
                }
            }
            return "";
        }
        #endregion

        #region "   1.Add Add_MouseEvent"
        void Add_Event(System.Windows.Forms.Control ctrl)
        {
            ctrl.Click += new EventHandler(Label_Click);
            //ctrl.MouseMove += new MouseEventHandler(pic_MouseDrag);
            //ctrl.MouseDown += new MouseEventHandler(pic_MouseDown);
            //this.loadControl(ctrl);
        }

        #endregion

        #region "   getFontStyle"
        private FontStyle getFontStyle(string FontStyleName)
        {
            if (FontStyleName.IndexOf("Bold") >= 0 && FontStyleName.IndexOf("Italic") >= 0)
                return (FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            else if (FontStyleName.IndexOf("Bold") >= 0)
                return System.Drawing.FontStyle.Bold;
            else if (FontStyleName.IndexOf("Italic") >= 0)
                return System.Drawing.FontStyle.Italic;
            else
                return System.Drawing.FontStyle.Regular;
        }
        #endregion

        #region "   Refresh"
        void Refresh(System.Windows.Forms.Control _Label)
        {
            //if (_Label != null)
            //    if (_Label.ToString().IndexOf("HinhTron") >= 0)
            //        ((LabelHinhTron)_Label).Refresh();
            if (_Label.Region != null)
            {
                System.Drawing.Drawing2D.GraphicsPath Gp = new System.Drawing.Drawing2D.GraphicsPath();
                Gp.AddEllipse(0, 0, _Label.Size.Width - 1, _Label.Size.Height - 1);
                _Label.Region = new Region(Gp);
                Gp.Dispose();
                this.Refresh();
            }
        }
        #endregion

        #region "   Label getLabel"

        #region "   getPanel"
        Panel getPanel(DataRow _drDM_HH, int xdong, int ycot)
        {
            Panel pnlbanA = new Panel();
            //pnlbanA.BackColor = System.Drawing.Color.NavajoWhite;
            pnlbanA.BackColor = Color.FromArgb(254, 255, 153);//(255, 255, 128);
            //255, 255, 128

            pnlbanA.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            pnlbanA.Location = new System.Drawing.Point(140 * (ycot - 1) + 4, 80 * (xdong - 1) + 4);
            pnlbanA.Name = "lblMonAn" + _drDM_HH["OBJID"] + "";
            pnlbanA.Size = new System.Drawing.Size(140, 80);
            pnlbanA.TabIndex = 1;
            pnlbanA.Tag = _drDM_HH["OBJID"] + "#" +
                            _drDM_HH["OBJNAME"] + "#" +
                            _drDM_HH["GIA"] + "#" +
                            _drDM_HH["MADVT"] + "#" +
                            _drDM_HH["KHUYENMAI_PHANTRAM"] + "#" +
                            _drDM_HH["DM_MAYIN_BEP_MA"] + "#" +
                            _drDM_HH["Vat"] + "#" +
                            _drDM_HH["BAN_GIA_MO"] + "#" +
                            _drDM_HH["DM_NHOMCHUHH_CODE"];

            //pnlbanA.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            pnlbanA.BorderStyle = BorderStyle.None;
            pnlbanA.BackgroundImageLayout = ImageLayout.Zoom;
            this.Add_Event(pnlbanA);
            //
            //PictureBox pic = this.getLabel_Left(pnlbanA, _drDM_HH);

            //Label _lblRight = this.getLabel_Right(pnlbanA, _drDM_HH);
            //if (!pic.Visible)
            //    _lblRight.Dock = DockStyle.Fill;

            Label lblTonKho = this.getLabel_TonKho(pnlbanA, _drDM_HH);

            pnlbanA.Text = _drDM_HH["OBJNAME"] + "\n" + float.Parse("0" + _drDM_HH["GIA"]).ToString("N0");
            //pnlbanA.Text = _lblRight.Text;
            //_lblRight.Text = "";
            //pnlbanA.Controls.Add(pic);
            //pnlbanA.Controls.Add(_lblRight);

            pnlbanA.Controls.Add(lblTonKho);
            //_lblRight.Controls.Add(lblTonKho);

            pnlbanA.Cursor = Cursors.Hand;
            return pnlbanA;
        }
        #endregion

        #region "   getLabel_Left"
        PictureBox getLabel_Left(System.Windows.Forms.Control ParentControl, DataRow _drDM_HH)
        {
            PictureBox pictureBox1 = new PictureBox();

            this.SetHinhAnh(pictureBox1, _drDM_HH["HINH"]);
            pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            //pictureBox1.Dock = System.Windows.Forms.DockStyle.Left;
            pictureBox1.Location = new System.Drawing.Point(0, 7);
            pictureBox1.Name = "pic" + _drDM_HH["OBJID"];
            pictureBox1.Size = new System.Drawing.Size(35, 44);
            pictureBox1.TabIndex = 0;
            pictureBox1.TabStop = false;
            pictureBox1.Visible = !(pictureBox1.BackgroundImage == null);

            pictureBox1.Tag = ParentControl.Tag + "";

            this.Add_Event(pictureBox1);
            pictureBox1.Cursor = Cursors.Hand;//#
            //
            return pictureBox1;
        }
        #endregion

        #region "   getLabel_Right"
        Label getLabel_Right(System.Windows.Forms.Control ParentControl, DataRow _drDM_HH)
        {
            Label lblbanA_tmp = new Label();
            lblbanA_tmp.BackColor = System.Drawing.Color.Transparent;//.BackColor = ParentControl.BackColor;
            //lblbanA_tmp.Dock = System.Windows.Forms.DockStyle.Fill;
            lblbanA_tmp.Font = new System.Drawing.Font("Times New Roman", 11.25F, System.Drawing.FontStyle.Bold);

            lblbanA_tmp.Location = new System.Drawing.Point(45, 0);
            lblbanA_tmp.ForeColor = System.Drawing.SystemColors.Desktop;// System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));

            lblbanA_tmp.Name = "lblRight" + _drDM_HH["OBJID"];
            lblbanA_tmp.Size = new System.Drawing.Size(95, 60);

            lblbanA_tmp.Text = _drDM_HH["OBJNAME"] + "\n" + float.Parse("0" + _drDM_HH["GIA"]).ToString("N0");
            lblbanA_tmp.Text = lblbanA_tmp.Text.ToUpper();

            lblbanA_tmp.TabIndex = 1;
            lblbanA_tmp.Tag = ParentControl.Tag + "";
            lblbanA_tmp.TextAlign = System.Drawing.ContentAlignment.TopCenter;
            lblbanA_tmp.BorderStyle = BorderStyle.None;
            this.Add_Event(lblbanA_tmp);
            lblbanA_tmp.Cursor = Cursors.Hand;//#
            //
            return lblbanA_tmp;
        }
        #endregion

        #region "   getLabel_TonKho"
        Label getLabel_TonKho(System.Windows.Forms.Control ParentControl, DataRow _drDM_HH)
        {
            Label lblTon_Kho = new Label();
            lblTon_Kho.AutoSize = true;
            lblTon_Kho.BackColor = System.Drawing.Color.Green;
            lblTon_Kho.Font = new System.Drawing.Font("Times New Roman", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            lblTon_Kho.ForeColor = System.Drawing.Color.White;
            lblTon_Kho.Location = new System.Drawing.Point(5, ParentControl.Height - 20);//45
            lblTon_Kho.Name = "lblTon_Kho" + _drDM_HH["OBJID"];
            lblTon_Kho.Size = new System.Drawing.Size(14, 18);
            lblTon_Kho.TabIndex = 8;

            lblTon_Kho.Text = decimal.Parse(_drDM_HH["TONKHO"] + "").ToString("N0");

            lblTon_Kho.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            lblTon_Kho.UseCompatibleTextRendering = true;
            lblTon_Kho.BorderStyle = BorderStyle.None;
            return lblTon_Kho;
        }
        #endregion

        #endregion

        #region "   convert2LabelHinhTron"
        void convert2LabelHinhTron(System.Windows.Forms.Control ctrl)
        {
            System.Drawing.Drawing2D.GraphicsPath Gp = new System.Drawing.Drawing2D.GraphicsPath();
            Gp.AddEllipse(0, 0, ctrl.Size.Width - 1, ctrl.Size.Height - 1);
            ctrl.Region = new Region(Gp);
            Gp.Dispose();
            this.Refresh();
        }
        #endregion

        #region "   getBackColor"
        Color getBackColor(string _TrangThai)
        {
            if (_TrangThai == "0")//Chưa có khách
                return Color.White;
            else if (_TrangThai == "1")//Có khách
                return Color.SpringGreen;
            else //if (_TrangThai == "2")//'Đã đặt trước
                return Color.Yellow;
        }
        #endregion

        #region "   setNoneMesssage"
        void setNoneMesssage()
        {
            //ochon = chon.None;
            //lblMessage.Text = "";
        }
        #endregion

        #region "   timer1_Tick"
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (bLoadform)
            {
                try
                {
                    if (timer1.Tag + "" != "")
                    {
                        DateTime dt = (DateTime)timer1.Tag;
                        lbel_ngayhienhanh.Text = dt.ToString("dd/MM/yyyy") + "(" + this.V2E(dt.DayOfWeek + "") + ")\n";
                        lbel_ngayhienhanh.Text += dt.ToString("hh:mm:ss tt");

                        if (ochon == chon.MenhGia)
                            this.lblMenhGia_ThanhToan.BackColor = this.RandomColor();
                        else
                            this.lblMenhGia_ThanhToan.BackColor = cMauNen_lblMenhGia_ThanhToan;

                        if (ochon == chon.ChinhSuaHH)
                            this.lblChinhSua.BackColor = this.RandomColor();
                        else
                            this.lblChinhSua.BackColor = cMauNen_lblChinhSua;

                        if (ochon == chon.GiaBan)
                            this.lblGiaBan.BackColor = this.RandomColor();
                        else
                            this.lblGiaBan.BackColor = cMauNen_lblGiamGia;


                        timer1.Tag = dt.AddSeconds(1);
                    }
                }
                catch (Exception ex)
                {
                    timer1.Tag = DateTime.Now;
                    string s = ex.Message;
                }
            }
        }
        Color RandomColor()
        {
            Random lRandom = new Random();
            int chiSoMau1 = lRandom.Next(0, 255);
            int chiSoMau2 = lRandom.Next(0, 255);//100, 150
            int chiSoMau3 = lRandom.Next(0, 255);//0, 50
            return Color.FromArgb(chiSoMau1, chiSoMau2, chiSoMau3);
        }
        #endregion

        #region "   V2E"
        string V2E(string dayofWeek)
        {
            return dayofWeek.Replace("Monday", "T2").Replace("Tuesday", "T3").Replace("Wednesday", "T4").Replace("Thursday", "T5").Replace("Friday", "T6").Replace("Saturday", "T7").Replace("Sunday", "CN");
        }
        #endregion

        #region "   gvNhom_Mon_FocusedRowChanged"
        private void gvNhom_Mon_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {//grdDM_NHOMHH_Click
            if (bLoadform)
            {
                if (this.Cursor == Cursors.WaitCursor)
                    return;
                this.Cursor = Cursors.WaitCursor;
                //pnlSoDo_MonAn.Controls.Clear();
                try
                {
                    string sNhom_Mon_ma = "";
                    if (gvNhom_Mon.GetSelectedRows().Length > 0)
                    {
                        int row = gvNhom_Mon.GetSelectedRows()[0];
                        for (int j = 0; j < gvNhom_Mon.VisibleColumns.Count; j++)
                        {
                            sNhom_Mon_ma = gvNhom_Mon.GetDataRow(row)["OBJID"] + "";
                            goto here;
                        }
                    }
                //else
                //    pnlSoDo_MonAn.Controls.Clear();

                here:
                    if (sNhom_Mon_ma != "")
                    {
                        //MessageBox.Show(sNhom_Mon_ten, sNhom_Mon_ma);
                        //string sMaKhuVuc = this.GetSelectedValues(gridView1, "OBJID");
                        if (sNhom_Mon_ma + "" != "")
                        {
                            this.ShowData(sNhom_Mon_ma);
                            DataTable tbDM_NHOMHH = (DataTable)grdDM_NHOMHH.DataSource;
                            int iMau = 0;
                            for (int i = 0; i < tbDM_NHOMHH.Rows.Count; i++)
                            {
                                if (tbDM_NHOMHH.Rows[i]["OBJID"] + "" == sNhom_Mon_ma)
                                    tbDM_NHOMHH.Rows[i]["STT"] = 4;
                                else
                                    tbDM_NHOMHH.Rows[i]["STT"] = iMau++;
                                if (iMau == 4)
                                    iMau = 0;
                            }
                        }
                        new cpublic().Registry_Set(this.Name + gvNhom_Mon.Name, sNhom_Mon_ma);
                    }
                }
                catch (Exception ex)
                {
                    new mh_thongbao("gvNhom_Mon_FocusedRowChanged:\n" + ex.Message, 2).ShowDialog();
                }
                this.Cursor = Cursors.Default;
            }
        }
        #endregion

        #region "   Banner Bottom..........................................."
        #region "   lblxoa_ThucDon_Click"
        private void lblxoa_ThucDon_Click(object sender, EventArgs e)
        {
            if (tbBH_PHIEU_CT_TMP.Rows.Count == 0) return;
            try
            {
                ochon = chon.None;
                DataRow dr = gvHoaDon_CT.GetDataRow(gvHoaDon_CT.FocusedRowHandle);
                if (dr != null)
                {

                    string _OBJID = dr["OBJID"] + "";

                    if (_OBJID != "" && _OBJID != "-1")
                    { //
                        string sKHONG_XOA_MON_SAU_TAM_TINH = new cpublic().KiemTra_CoQuyen("mh_banhang_CT", "lblxoa_ThucDon", 1) + ""; //Variable.tbBH_CAU_HINH.Rows[0]["KHONG_XOA_MON_SAU_TAM_TINH"] + "";
                        if (sKHONG_XOA_MON_SAU_TAM_TINH == "True")
                        {
                            new mh_thongbao("Không được xóa món đã tạm tính.", 2).ShowDialog();
                            return;
                        }
                    }

                    if (new mh_thongbao("Bạn muốn " + lblxoa_ThucDon.Text.Replace("\n", " ").Trim().ToLower() + "?", 3).ShowForm() == DialogResult.OK)
                    {
                        string sKHONG_XOA_MON_SAU_TAM_TINH = new cpublic().KiemTra_CoQuyen("mh_banhang_CT", "lblxoa_ThucDon", 1) + ""; //Variable.tbBH_CAU_HINH.Rows[0]["KHONG_XOA_MON_SAU_TAM_TINH"] + "";
                        if (_OBJID != "" && _OBJID != "-1")
                        {
                            string sPHAI_NHAP_LYDO_TRA_MON = Variable.tbBH_CAU_HINH.Rows[0]["PHAI_NHAP_LYDO_TRA_MON"] + "";
                            if (sPHAI_NHAP_LYDO_TRA_MON == "True")
                            {
                                mh_chu omh_chu = new mh_chu();
                                string sLyDoTraMon = omh_chu.ShowForm("Lý do xóa món", dr["GHI_CHU"] + "", 200, 200, false);
                                if (omh_chu.DialogResult != DialogResult.OK)
                                    return;
                                dr["GHI_CHU"] = sLyDoTraMon;
                            }
                        }

                        int irt = -1;
                        if (_OBJID != "-1")
                            irt = new thuvien().SP_Update("sp_mh_banhang_sua",
                                                            new string[] { "@flag", "@OBJID" },
                                                            new object[] { 9, _OBJID });
                        else
                        {
                            irt = new thuvien().SP_Update("sp_mh_banhang_sua",
                                                            new string[] { "@flag", "@BH_PHIEU_MA", "@MAHH" },
                                                            new object[] { 21, tbBH_PHIEU_TMP.Rows[0]["OBJID"], dr["MAHH"] });
                            //tbBH_PHIEU_CT_TMP.Rows.Remove(dr);
                        }

                        //if ((irt > 0) || (_OBJID == "-1" && irt == -1))
                        if ((irt > 0) || (_OBJID == "-1"))
                        //if (_OBJID == "-1")
                        {
                            if (_OBJID != "-1")
                                drBH_PHIEU_CT_TMP = tbBH_PHIEU_CT_TMP.Select("OBJID=" + _OBJID)[0];
                            else if (ihandle >= 0 && tbBH_PHIEU_CT_TMP.Rows.Count > 0)
                            {
                                //drBH_PHIEU_CT_TMP = tbBH_PHIEU_CT_TMP.Rows[0];
                                tbBH_PHIEU_CT_TMP.Columns["THANH_TIEN"].Expression = null;
                                tbBH_PHIEU_CT_TMP.Columns["THANH_TIEN"].ReadOnly = false;
                                tbBH_PHIEU_CT_TMP.Columns["GIA_BAN"].Expression = null;
                                tbBH_PHIEU_CT_TMP.Columns["GIA_BAN"].ReadOnly = false;
                                drBH_PHIEU_CT_TMP.ItemArray = dr.ItemArray;
                                tbBH_PHIEU_CT_TMP.Columns["THANH_TIEN"].Expression = "SO_LUONG * DON_GIA - CHIETKHAU_TIEN";// - CHIETKHAU_TIEN + VAT_TIEN";
                                tbBH_PHIEU_CT_TMP.Columns["GIA_BAN"].Expression = "DON_GIA";
                            }

                            if (drBH_PHIEU_CT_TMP != null)
                            {
                                if (drBH_PHIEU_CT_TMP["MAHH"] + "" != "Tien_Gio" && _OBJID != "-1")
                                {
                                    drBH_PHIEU_CT_TMP["OBJNAME_HH_root"] = "(CANCEL)" + drBH_PHIEU_CT_TMP["OBJNAME_HH_root"];
                                    this.Add_DataRow_tbDeletePhieuCT(drBH_PHIEU_CT_TMP, drBH_PHIEU_CT_TMP["SO_LUONG"]);//20101019
                                }
                                //tbBH_PHIEU_CT_TMP.Rows.Remove(drBH_PHIEU_CT_TMP);
                                tbBH_PHIEU_CT_TMP.Rows.Remove(dr);
                                tbBH_PHIEU_CT_TMP.AcceptChanges();
                                grdBH_PHIEU.Refresh();
                            }

                            if (ihandle > tbBH_PHIEU_CT_TMP.Rows.Count - 1 && ihandle > 0)
                                --ihandle;

                            this.SetSelectRow();
                        }
                        this.TinhTongSUM();
                        //this.gvNhom_Mon_FocusedRowChanged(null, null);
                        this.Load_TonKHO_1Mon(_OBJID);//20101214
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox_LPV.Show("Thông báo\n" + ex.Message);
            }
        }
        #endregion

        #region "   Add_DataRow"
        void Add_DataRow_tbDeletePhieuCT(DataRow _drDel, object _Qty_Del)
        {
            string sOBJNAME_HH = _drDel["OBJNAME_HH"] + "";
            if (sOBJNAME_HH.IndexOf("(CANCEL)") < 0)
                _drDel["OBJNAME_HH"] = "(CANCEL)" + _drDel["OBJNAME_HH"];

            string _OBJID = "0" + _drDel["OBJID"] + "";
            float iSoLuongTru = 0;
            float.TryParse(_Qty_Del + "", out iSoLuongTru);
            if (iSoLuongTru > 0)
            {
                iSoLuongTru = -iSoLuongTru;
                _drDel["SO_LUONG"] = iSoLuongTru;
            }
            DataRow[] _drs = tbDeletePhieuCT.Select("OBJID = " + _OBJID.Replace("0-", "-0") + "");
            if (_drs.Length > 0)
            {//exists                
                float iSoLuong = 0;
                float.TryParse(_drs[0]["SO_LUONG"] + "", out iSoLuong);

                _drs[0]["SO_LUONG"] = iSoLuong + iSoLuongTru;
            }
            else
            {//not exists
                DataRow drDel = tbDeletePhieuCT.NewRow();
                drDel.ItemArray = _drDel.ItemArray;
                tbDeletePhieuCT.Rows.Add(drDel);
            }
            foreach (DataRow dr1 in tbDeletePhieuCT.Select("SO_LUONG = 0"))
            {
                tbDeletePhieuCT.Rows.Remove(dr1);
                tbDeletePhieuCT.AcceptChanges();
            }
        }
        #endregion

        #region "   lblHuy_HoaDon_Click"
        private void lblHuy_HoaDon_Click(object sender, EventArgs e)
        {
            ochon = chon.None;
            if (new mh_thongbao("Bạn muốn " + lblHuy_HoaDon.Text.Replace("\n", " ").Trim().ToLower() + "?", 3).ShowForm() == DialogResult.OK)
                this.Huy_HoaDon();
        }
        private void Huy_HoaDon()
        {

            string id = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
            if (id != "")
            {
                int irt = new thuvien().SP_Update("sp_mh_banhang_sua",
                                                    new string[] { "@flag", "@OBJID", "@DM_BAN_MA" },
                                                    new object[] { 8, id, sBAN_MA });
            }
            this.ShowInfo_Config();

            this.New_mh_banhang_CT();
        }
        #endregion

        #region "   lblGiamGia_HoaDon_Click"
        private void lblGiamGia_HoaDon_Click(object sender, EventArgs e)
        {
            ochon = chon.None;
            mh_dmgiamgia omh_dmgiamgia = new mh_dmgiamgia();
            DataRow drgiamgia = omh_dmgiamgia.ShowForm();
            if (drgiamgia != null)
            {
                int iMA_LOAI_GIAMGIA = int.Parse("0" + drgiamgia["MA_LOAI_GIAMGIA"]);//1: 
                string sGIATRI = drgiamgia["GIATRI"] + "";
                string sOBJNAME = drgiamgia["OBJNAME"] + "";
                this.GiamGia(iMA_LOAI_GIAMGIA, sGIATRI);
                //MessageBox.Show(sGIATRI, sOBJNAME, MessageBoxButtons.OK);
                grdBH_PHIEU.Refresh();

            }
        }
        void GiamGia(int iMA_LOAI_GIAMGIA, string sGIATRI)
        {
            if (iMA_LOAI_GIAMGIA <= 2)
            { //LOAI AN hoặc UONG
                foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Select("NHOMCHUHH_CODE='" + iMA_LOAI_GIAMGIA + "'"))
                {
                    drBH_PHIEU_CT_TMP = dr;
                    //db1 = this.tinh_phantram(double.Parse("" + lblCTHD_ChietKhau1.Tag), sGIATRI, lblCTHD_ChietKhau1);
                    //dr["CHIETKHAU_TIEN"] = db1;
                    /////
                    if (sGIATRI.IndexOf("%") > 0 && new cpublic().IsNumeric(sGIATRI.Trim().Replace("%", "").Trim()))
                    {
                        dr["CHIETKHAU_PHANTRAM"] = int.Parse(sGIATRI.Trim().Replace("%", "").Trim());

                        int iDON_GIA = int.Parse(dr["DON_GIA"] + "");
                        float iSO_LUONG = int.Parse(dr["SO_LUONG"] + "");
                        Double dCHIETKHAU_TIEN = this.tinh_phantram(iDON_GIA * iSO_LUONG, sGIATRI, new Label());
                        dr["CHIETKHAU_TIEN"] = dCHIETKHAU_TIEN;
                    }
                    this.RefreshCTHD(true);
                }
            }
            else if (iMA_LOAI_GIAMGIA <= 3)
            {//ap dụng cho Hoa_DonCT.Current_Row
                double db1 = 0;
                db1 = this.tinh_phantram(double.Parse("" + lblCTHD_ChietKhau1.Tag), sGIATRI, lblCTHD_ChietKhau1);
                drBH_PHIEU_CT_TMP["CHIETKHAU_TIEN"] = db1;
                /////
                if (sGIATRI.IndexOf("%") > 0 && new cpublic().IsNumeric(sGIATRI.Trim().Replace("%", "").Trim()))
                    drBH_PHIEU_CT_TMP["CHIETKHAU_PHANTRAM"] = int.Parse(sGIATRI.Trim().Replace("%", "").Trim());
                this.RefreshCTHD(true);
            }
            else if (iMA_LOAI_GIAMGIA <= 4)
            {//Ap dụng cho Hoa_Don
                int itiengio = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["TIEN_GIO"]);
                int ithanhtien = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"]);

                foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Select(""))
                {
                    drBH_PHIEU_CT_TMP = dr;
                    //db1 = this.tinh_phantram(double.Parse("" + lblCTHD_ChietKhau1.Tag), sGIATRI, lblCTHD_ChietKhau1);
                    //dr["CHIETKHAU_TIEN"] = db1;
                    /////
                    if (sGIATRI.IndexOf("%") > 0 && new cpublic().IsNumeric(sGIATRI.Trim().Replace("%", "").Trim()))
                    {
                        dr["CHIETKHAU_PHANTRAM"] = int.Parse(sGIATRI.Trim().Replace("%", "").Trim());

                        int iDON_GIA = int.Parse(dr["DON_GIA"] + "");
                        float iSO_LUONG = int.Parse(dr["SO_LUONG"] + "");
                        Double dCHIETKHAU_TIEN = this.tinh_phantram(iDON_GIA * iSO_LUONG, sGIATRI, new Label());
                        dr["CHIETKHAU_TIEN"] = dCHIETKHAU_TIEN;
                    }
                    this.RefreshCTHD(true);
                }
                this.lblTongCong_Click(null, null);
            }
            this.TinhTongSUM();

        }
        #endregion

        #region "   lblPhi_DichVu_Click"
        private void lblDoi_Diem_Click(object sender, EventArgs e)
        {
            ochon = chon.None;

            if (tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] + "" == "")
                tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] = sMaThe_VIP;
            if (tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] + "" == "")
            {
                mh_so omh_so = new mh_so(false, "Nhập mã thẻ khách hàng");
                omh_so.eClick += new EventHandler(Kiem_Tra_The);
                omh_so.ShowDialog();
                if (omh_so.DialogResult != DialogResult.OK)
                    return;

                sMaThe_VIP = omh_so.txt_ketqua.Text;

            }

            DateTime dt = (DateTime)timer1.Tag;
            mh_banhang_CT_Doi_Diem omh_banhang_CT_Doi_Diem = new mh_banhang_CT_Doi_Diem(sMaThe_VIP, dt);
            string DM_KHUYENMAI_MA = omh_banhang_CT_Doi_Diem.ShowForm();
            if (omh_banhang_CT_Doi_Diem.DialogResult == DialogResult.OK)
            {
                tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] = sMaThe_VIP;
                tbBH_PHIEU_TMP.Rows[0]["DM_KHUYENMAI_MA"] = DM_KHUYENMAI_MA;
                //this.Load_TenKhachHangVIP();
                this.HienThi_oTheoNGay_Gio();
            }
        }
        #endregion
        #region "   KiemTra The"
        void Kiem_Tra_The(object sender, EventArgs e)
        {
            if (sender != null)
            {
                mh_so omh_so = (mh_so)sender;
                string The_Vip_Ma = omh_so.txt_ketqua.Text;
                string sSQL = "SELECT 1 FROM DM_THE WHERE CODE LIKE '" + The_Vip_Ma + "'";

                DataTable tbTheVIP = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });
                if (tbTheVIP.Rows.Count == 0)
                {
                    omh_so.DialogResult = DialogResult.No;
                    new mh_thongbao("MÃ SỐ không hợp lệ", 2).ShowForm();
                }
                else
                {
                    omh_so.DialogResult = DialogResult.OK;
                    omh_so.Dispose();
                }
            }
        }
        #endregion

        #region "   lblGhi_Chu_Click"
        private void lblGhi_Chu_Click(object sender, EventArgs e)
        {
            ochon = chon.None;
            if (drBH_PHIEU_CT_TMP == null)
            {
                MessageBox_LPV.Show("Chưa có thực đơn nào để ghi chú.");
                return;
            }
            if (tbBH_PHIEU_CT_TMP.Rows.Count == 0) return;
            if (drBH_PHIEU_CT_TMP["OBJID"] + "" == "" || drBH_PHIEU_CT_TMP["OBJID"] + "" == "-1")
            {
                string sghichu = drBH_PHIEU_CT_TMP["GHI_CHU"] + "";
                frmDM_GHU_CHU_BEP ofrmDM_GHU_CHU_BEP = new frmDM_GHU_CHU_BEP(sghichu, drBH_PHIEU_CT_TMP["OBJNAME_HH"] + "", drBH_PHIEU_CT_TMP["MAHH"] + "");
                sghichu = ofrmDM_GHU_CHU_BEP.ShowForm();

                //mh_chu omh_chu = new mh_chu();
                //sghichu = omh_chu.ShowForm(sghichu, 300, 250, false);
                ////sghichu = new cpublic().loadformchu_point(sghichu, 300, 250);
                //if (omh_chu.DialogResult == DialogResult.OK)
                //{
                drBH_PHIEU_CT_TMP["GHI_CHU"] = sghichu;
                if (sghichu.Trim() != "")
                    sghichu = " (" + sghichu + ")";
                drBH_PHIEU_CT_TMP["OBJNAME_HH"] = drBH_PHIEU_CT_TMP["OBJNAME_HH_root"] + sghichu;
                grdBH_PHIEU.Refresh();
                this.TinhTongSUM();
                //}
            }
            else
            {
                new Mod_messagebox().messagebox_pos("Thông báo", "Dữ liệu đã được lưu\nKhông thể thêm ghi chú", 2);
            }
        }
        #endregion

        #region "   lblChinhSua_Click"
        private void lblChinhSua_Click(object sender, EventArgs e)
        {
            if (Variable.username == "") return;

            if (ochon == chon.ChinhSuaHH)
                ochon = chon.None;
            else
            {
                if (!new cpublic().KiemTra_CoQuyen(this.Name, ((System.Windows.Forms.Control)sender).Name, 1))
                {
                    MessageBox_LPV.Show("Bạn không có quyền");
                    return;
                }
                ochon = chon.ChinhSuaHH;


            }
            //mh_dm_HangHoa_chinhSua omh_dm_HangHoa_chinhSua = new mh_dm_HangHoa_chinhSua("");
            //omh_dm_HangHoa_chinhSua.ShowDialog();

        }
        #endregion

        #region "   lblTamTinh_Click"
        private void lblTamTinh_Click(object sender, EventArgs e)
        {//tinh tien gio
            if (lblTamTinh.Text == "")
                return;
            //this.Cursor = Cursors.WaitCursor;
            ////        ' ''        'Print logo downloaded bit image
            ////' ''        If gblnPRINTGRAPHICLOGO Then
            ////' ''            '------------------------------------------------
            ////' ''            psrlCOMport.Write(Chr(28) & Chr(112) & Chr(1) & Chr(0))
            ////' ''            '------------------------------------------------
            ////' ''        End If
            //this.lblTamTinh_Click(true);
            //this.Cursor = Cursors.Default;

            //if (iHINH_THUC_BAN_HANG == 1)//ban
            //{
            //    this.DialogResult = DialogResult.OK;
            //    this.Dispose();
            //}
            //else if (iHINH_THUC_BAN_HANG == 2)//ban & Thuc Don
            //{
            //    mh_banhang omh_banhang = new mh_banhang(lbel_tencongty.Text);
            //    omh_banhang.ShowDialog();
            //}
            if (tbDM_LOAIDICHVU.Rows.Count > 0)
            {
                //lblLoaiDichVu.Text = tbDM_LOAIDICHVU.Rows[0]["OBJNAME"] + "";
                //lblLoaiDichVu.Tag = tbDM_LOAIDICHVU.Rows[0]["OBJNAME"] + "";

                //if (tbDM_LOAIDICHVU.Rows[0]["CO_TINHGIO_THEONGAY"] + "" != "True")
                //    lblCoTinhGio_TheoNgay.Text = "";

                //if (tbDM_LOAIDICHVU.Rows[0]["CAT_THOIGIAN"] + "" != "True")
                //    lblCatCo.Text = "";//20110402_bo

                if (tbDM_LOAIDICHVU.Rows[0]["CO_TINH_TIENGIO"] + "" == "True")
                {
                    //if (tbBH_PHIEU_CT_TMP.Select("MaHH LIKE 'Tien_Gio'").Length == 0)
                    this.Tinh_Tien_Gio_Click();

                }


            }

        }
        private void lblTamTinh_Click(Boolean iCoInBill)
        {
            //
            ochon = chon.None;
            string sMaphieu = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
            tbBH_PHIEU_TMP.Rows[0]["NGUOI_LAP"] = Variable.username;

            if (!iCoInBill)
                this.Load_TienTIP();

            if (tbBH_PHIEU_CT_TMP.GetChanges() != null)
                this.LoadVAT_AnTaiCho_MangVe();

            this.TinhTongTien();

            this.In_TamTinh_Bep();

            this.Luu_TamTinh();
            if (iCoInBill)
            {
                ////print_usb
                //DataTable tb = new thuvien().SP_SelectDataTable("sp_DM_MAYIN_HD", null, null);
                //DataView dv = tb.DefaultView;
                //dv.Sort = "COMNAME";
                //int vitri = dv.Find(new object[] { "USB" });
                //if (vitri > -1)
                //{
                //    // in bill theo ha noi
                //    mh_viewhoadon mh = new mh_viewhoadon();
                //    mh.InBill(sMaphieu);
                //}
                //else
                this.In_TamTinh_Bill();
            }
        }
        #endregion

        void In_TamTinh6cot()
        {
            PrintCOMs oPrintCOMs = new PrintCOMs(PrintCOMs.Print_Type.Print_BILL);
            SerialPort_LPV[] aSerialPort_LPV = oPrintCOMs.Print_Start();
            try
            {
                foreach (SerialPort_LPV oSerialPort_LPV in aSerialPort_LPV)
                {
                    if (oSerialPort_LPV != null)
                    {
                        oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, "KP GROUP", "Sales", "Balance", "Amount", "Count", "Ratio");
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, '-', PrintCOMs.Fills.Fills_Full);

                        for (int i = 0; i < 50; i++)
                            oPrintCOMs.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, i * 100 + "", i * 200 + "", i * 300 + "", i * 400 + "", i * 500 + "", i * 600 + "");
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, ' ', PrintCOMs.Fills.Fills_Full);
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, ' ', PrintCOMs.Fills.Fills_Full);
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, ' ', PrintCOMs.Fills.Fills_Full);
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, ' ', PrintCOMs.Fills.Fills_Full);
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, ' ', PrintCOMs.Fills.Fills_Full);
                        oPrintCOMs.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, ' ', PrintCOMs.Fills.Fills_Full);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                oPrintCOMs.Print_Close();
            }
        }

        #region "   In_TamTinh_Bep"
        void In_TamTinh_Bep()
        {
            thuvien othuvien = new thuvien();
            //string i1 = 32;
            //string i2 = 14;
            //string i3 = 10;   // = 56
            string sMaphieu = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
            string sNguoiLap = tbBH_PHIEU_TMP.Rows[0]["Nguoi_Lap"] + "";
            string sTennv = "";
            if (sNguoiLap != "")
            {
                string sSQL = "SELECT NV.OBJNAME " +
                              "FROM DM_NHANVIEN NV " +
                              "      INNER JOIN DM_DANGNHAP DN ON NV.OBJID = DN.MA_NHANVIEN  " +
                              "WHERE DN.USERNAME LIKE '" + sNguoiLap + "'";

                DataTable tbTenNhanVien = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
                if (tbTenNhanVien.Rows.Count > 0)
                {
                    sTennv = tbTenNhanVien.Rows[0]["OBJNAME"] + "";
                    tbBH_PHIEU_TMP.Rows[0]["TENNV"] = sTennv;
                }
            }

            cpublic ocpublic = new cpublic();
            try
            {
               // chuong 123
                #region "   In_TamTinh_Bep"
                //if (sMaphieu.Trim() != "" && (tbDeletePhieuCT.Rows.Count > 0 || tbBH_PHIEU_CT_TMP.Select("OBJID IS NULL OR OBJID = -1").Length > 0))
                //{
                //    sMaphieu = "No: " + sMaphieu;
                //    string sTieuDe_MoRong = "(Thêm)";
                //    if (tbBH_PHIEU_CT_TMP.Select("(OBJID IS NULL OR OBJID = -1)").Length == tbBH_PHIEU_CT_TMP.Select("").Length)
                //        sTieuDe_MoRong = "(Mới)";
                //    Boolean bInGia = false;
                //    Boolean bIN_TEN_HANGHOA = false;
                //    Boolean bIN_TEN_BAN = false;
                //    Boolean bIN_SO_HOADON = false;

                //    #region "   tbDM_MAYIN_BEP_CAUHINH"
                //    DataTable tbDM_MAYIN_BEP_CAUHINH = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { "SELECT * FROM DM_MAYIN_BEP_CAUHINH" });
                //    if (tbDM_MAYIN_BEP_CAUHINH.Rows.Count > 0)
                //    {
                //        bInGia = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_GIA"] + "") == "True";
                //        bIN_SO_HOADON = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_SO_HOADON"] + "") == "True";
                //        bIN_TEN_BAN = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_TEN_BAN"] + "") == "True";
                //        bIN_TEN_HANGHOA = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_TEN_HANGHOA"] + "") == "True";
                //    }

                //    #endregion

                //    PrintCOMs oPrintCOM = new PrintCOMs(PrintCOMs.Print_Type.Print_KitChen);
                //    SerialPort_LPV[] SerialPort_LPVs = oPrintCOM.Print_Start();
                //    if (SerialPort_LPVs != null)
                //    {
                //        string _Ghi_Chu = "";
                //        string _TenHangHoa = "";

                //        foreach (SerialPort_LPV oSerialPort_LPV in Variable.gsrlCOMBillport)
                //        {
                //            if (oSerialPort_LPV != null)//&& oSerialPort_LPV.IsOpen)
                //            {
                //                if (!oSerialPort_LPV.IsOpen)
                //                    oSerialPort_LPV.Open();
                //                if (tbDeletePhieuCT.Select("DM_MAYIN_BEP_MA = '" + oSerialPort_LPV.OBJID + "'").Length > 0 ||
                //                    tbBH_PHIEU_CT_TMP.Select("(OBJID IS NULL OR OBJID = -1) AND DM_MAYIN_BEP_MA = '" + oSerialPort_LPV.OBJID + "'").Length > 0)
                //                {//Loc ra nhung may in cua SP do

                //                    #region  "  Top"

                //                    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Double_Height, "[" + oSerialPort_LPV.OBJNAME + "]" + sTieuDe_MoRong, "", "", "");

                //                    if (bIN_TEN_BAN && bIN_SO_HOADON)
                //                        oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Double_Height, lblKhuVuc_Ban.Text, "", "", sMaphieu);
                //                    else if (bIN_SO_HOADON)
                //                        oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Double_Height, sMaphieu, "", "", "");
                //                    else if (bIN_TEN_BAN)
                //                        oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Double_Height, lblKhuVuc_Ban.Text, "", "", "");

                //                    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Double_Height, "Ca: " + lblcalamviec.Text, "", "", "");
                //                    oPrintCOM.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, '=', PrintCOMs.Fills.Fills_Full);
                //                    #endregion

                //                    #region "   Content"
                //                    //tbDeletePhieuCT
                //                    string sCK_Giam = "";
                //                    string sVAT_Tang = "";
                //                    foreach (DataRow dr in tbDeletePhieuCT.Select("DM_MAYIN_BEP_MA = '" + oSerialPort_LPV.OBJID + "'"))
                //                    {
                //                        #region 
                //                        if (dr["DM_MAYIN_BEP_MA"] + "" == oSerialPort_LPV.OBJID)//.PortName
                //                        {
                //                            _TenHangHoa = dr["OBJNAME_HH_root"] + "";
                //                            if (!bIN_TEN_HANGHOA)
                //                                _TenHangHoa = "";
                //                            oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, _TenHangHoa, "", "", dr["SO_LUONG"] + "   ");

                //                            if (bInGia)
                //                                oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, "Gia: " + int.Parse("0" + dr["DON_GIA"]).ToString("N0"), "", "", "");

                //                            #region "   Tam thoi ghim lai -- chua xai"
                //                            //sCK_Giam = float.Parse(dr["CHIETKHAU_TIEN"] + "").ToString("N0");
                //                            //sVAT_Tang = float.Parse(dr["VAT_TIEN"] + "").ToString("N0");

                //                            //if (sCK_Giam != "" && sCK_Giam != "0")
                //                            //    oSerialPort_LPV.WriteLine(this.f_splitString2Column("--Discount: ", "-" + sCK_Giam, 56));

                //                            //if (sVAT_Tang != "" && sVAT_Tang != "0")
                //                            //    oSerialPort_LPV.WriteLine(this.f_splitString2Column("--VAT: ", sVAT_Tang, 56));
                //                            ////--------------------------------------------------------------------
                //                            #endregion

                //                            // tohoai
                //                            _Ghi_Chu = ("Ly do: " + dr["GHI_CHU"] + "").Trim();
                //                            if (_Ghi_Chu.Trim() != "")
                //                            {
                //                                string _Ghi_Chu_2 = "";
                //                                #region "   _Ghi_Chu_2"
                //                                if (_Ghi_Chu.Length >= 56)
                //                                {
                //                                    int iSpace = 0;
                //                                    int icount = 0;
                //                                    while (icount < 56)
                //                                    {
                //                                        if (_Ghi_Chu.IndexOf(' ', icount) == icount)
                //                                            iSpace = icount;
                //                                        icount++;
                //                                    }
                //                                    string sTmp = "";

                //                                    sTmp = _Ghi_Chu.Substring(0, iSpace).Trim();
                //                                    _Ghi_Chu_2 = _Ghi_Chu.Substring(iSpace).Trim();
                //                                    _Ghi_Chu = sTmp;

                //                                }
                //                                #endregion

                //                                string sPHAI_NHAP_LYDO_TRA_MON = Variable.tbBH_CAU_HINH.Rows[0]["PHAI_NHAP_LYDO_TRA_MON"] + "";
                //                                if (_Ghi_Chu.Trim() != "")//tra mon
                //                                {
                //                                    oSerialPort_LPV.WriteLine(ocpublic.RemoveSign4VietnameseString(_Ghi_Chu).Trim());
                //                                    if (_Ghi_Chu_2 != "")
                //                                        oSerialPort_LPV.WriteLine(ocpublic.RemoveSign4VietnameseString(_Ghi_Chu_2).Trim());
                //                                    // oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, "Ly do: " + _Ghi_Chu.Trim() + "", "", "", "");
                //                                }

                //                            }

                //                        }
                //                        #endregion
                //                    }

                //                    float iGia = 0;
                //                    float iSL = 0;
                //                    //tbBH_PHIEU_CT_TMP
                //                    foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Select("(OBJID IS NULL OR OBJID = -1) AND DM_MAYIN_BEP_MA = '" + oSerialPort_LPV.OBJID + "'"))
                //                    {
                //                        #region
                //                        //if (dr["DM_MAYIN_BEP_COMNAME"] + "" == oSerialPort_LPV.PortName)
                //                        {
                //                            _TenHangHoa = dr["OBJNAME_HH_root"] + "";
                //                            float.TryParse("" + dr["DON_GIA"], out iGia);
                //                            float.TryParse("" + dr["SO_LUONG"], out iSL);

                //                            if (!bIN_TEN_HANGHOA)
                //                                _TenHangHoa = "";
                //                            oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, _TenHangHoa, "", "", dr["SO_LUONG"] + "   ");

                //                            if (bInGia)
                //                                oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, "Gia: " + iGia.ToString("N0"), "", "", "");


                //                            //---------------------------------------
                //                            //tohoai
                //                            if (!string.IsNullOrEmpty(dr["GHI_CHU"] + ""))
                //                                _Ghi_Chu = "Ghi chu: " + dr["GHI_CHU"] + "";

                //                            if (_Ghi_Chu.Trim() != "")
                //                            {
                //                                string _Ghi_Chu_2 = "";
                //                                #region "   _Ghi_Chu_2"
                //                                if (_Ghi_Chu.Length >= 56)
                //                                {
                //                                    int iSpace = 0;
                //                                    int icount = 0;
                //                                    while (icount < 56)
                //                                    {
                //                                        if (_Ghi_Chu.IndexOf(' ', icount) == icount)
                //                                            iSpace = icount;
                //                                        icount++;
                //                                    }
                //                                    string sTmp = "";

                //                                    sTmp = _Ghi_Chu.Substring(0, iSpace).Trim();
                //                                    _Ghi_Chu_2 = _Ghi_Chu.Substring(iSpace).Trim();
                //                                    _Ghi_Chu = sTmp;

                //                                }

                //                                #endregion

                //                                //---------------------------------------

                //                                if (iSL >= 0)
                //                                {
                //                                    oSerialPort_LPV.WriteLine(ocpublic.RemoveSign4VietnameseString(_Ghi_Chu).Trim());
                //                                    if (_Ghi_Chu_2 != "")
                //                                        oSerialPort_LPV.WriteLine(ocpublic.RemoveSign4VietnameseString(_Ghi_Chu_2).Trim());
                //                                }

                //                                    //oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, "(" + _Ghi_Chu.Trim() + ")", "", "", "");
                //                                else//SL < 0 ==> tra mon
                //                                {
                //                                    oSerialPort_LPV.WriteLine(ocpublic.RemoveSign4VietnameseString(_Ghi_Chu).Trim().Replace("Ghi chu", "Lý do"));
                //                                    if (_Ghi_Chu_2 != "")
                //                                        oSerialPort_LPV.WriteLine(ocpublic.RemoveSign4VietnameseString(_Ghi_Chu_2).Trim());
                //                                }
                //                                // oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, "Ly do: " + _Ghi_Chu.Trim() + "", "", "", "");
                //                            }
                //                        }
                //                        #endregion
                //                    }
                //                    #endregion

                //                    #region "   Bottom"

                //                    oPrintCOM.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, '=', PrintCOMs.Fills.Fills_Full);
                //                    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, "Nhan vien: " + sTennv, "", "", "");

                //                    string Ngay = "* NGAY: " + ((DateTime)timer1.Tag).ToString("dd-MM-yyyy HH:mm") + " *";

                //                    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Double_Height, Ngay, "", "", "");

                //                    oPrintCOM.Print_Bottom(oSerialPort_LPV);
                //                    #endregion
                //                }
                //                if (oSerialPort_LPV.IsOpen)
                //                    oSerialPort_LPV.Close();
                //            }
                //        }
                //        oPrintCOM.Print_Close();
                //    }
                //}
                #endregion
                // end chuong 123
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                MessageBox_LPV.Show("Thông báo\n" + ex.Message);
            }
        }
        #endregion

        #region "   f_splitString2Column"
        string f_splitString2Column(string a, string b, int i)
        {//i: 56
            string str = "";
            str = a;
            str += new cpublic().Spacestring(i - a.Length - b.Length);
            str += b;
            return str;
        }
        #endregion

        #region "   In_TamTinh_Bill"
        void In_TamTinh_Bill()
        {
            string sMaphieu = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
            try
            {
                #region "   In BILL (Mở in hóa đơn)"
                if (lblBill_On.Text == "Mở in hóa đơn")
                {
                    print_BAN_HANG oprint_BAN_HANG = new print_BAN_HANG();
                    oprint_BAN_HANG.Print_PHIEU_BANHANG(tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "", false);
                }
                #endregion
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                MessageBox_LPV.Show("Thông báo\n" + ex.Message);
            }
        }
        #endregion

        #region "   In_TamTinh - bo"
        //void In_TamTinh()
        //{
        //    this.In_TamTinh_Bep();
        //    this.In_TamTinh_Bill();
        //}

        #region "   MergeDataRow"

        void MergeDataRow()
        { //tbBH_PHIEU_CT_TMP
            string sMaHH = "";
            float fSo_Luong = 0;
            float fdon_gia = 0;
            float fdon_gia_TMP = 0;
            float fSo_Luong_sub = 0;
            foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Select("SO_LUONG > 0", "MAHH, DON_GIA, color"))
            {
                float.TryParse(dr["DON_GIA"] + "", out fdon_gia_TMP);
                if (sMaHH == dr["MaHH"] + "" && fdon_gia_TMP == fdon_gia && dr["STT"] + "" == "")//= giá, = maHH
                {
                    float.TryParse(dr["SO_LUONG"] + "", out fSo_Luong_sub);

                    tbBH_PHIEU_CT_TMP.Select("MAHH='" + sMaHH + "' AND DON_GIA = " + fdon_gia_TMP, "MAHH")[0]["SO_LUONG"] = fSo_Luong + fSo_Luong_sub;
                    tbBH_PHIEU_CT_TMP.Rows.Remove(dr);
                    this.Refresh_VAT_CT(tbBH_PHIEU_CT_TMP.Select("MAHH='" + sMaHH + "'", "MAHH")[0]);
                    this.TinhTongSUM();
                }
                else
                {
                    float.TryParse(dr["SO_LUONG"] + "", out fSo_Luong);
                    float.TryParse(dr["DON_GIA"] + "", out fdon_gia);
                    sMaHH = dr["MaHH"] + "";
                }
            }
        }
        #endregion
        #endregion

        #region "   Luu_TamTinh"
        void Luu_TamTinh()
        {
            //if (tbBH_PHIEU_CT_TMP.Rows.Count > 0)
            //    if (tbBH_PHIEU_TMP.GetChanges() == null)
            //        return;
            string _CUSTOMER_ID = tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] + "";
            if (_CUSTOMER_ID == "" && sMaThe_VIP != "")
                tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] = sMaThe_VIP;

            //if (tbBH_PHIEU_TMP.GetChanges() != null)
            {//neu co thay đổi dữ liệu thì --> luu
                string sGOP_MON_CUNG_TEN_KHI_DAT_HANG = Variable.tbBH_CAU_HINH.Rows[0]["GOP_MON_CUNG_TEN_KHI_DAT_HANG"] + "";
                if (sGOP_MON_CUNG_TEN_KHI_DAT_HANG == "True")
                    this.MergeDataRow();
                thuvien othuvien = new thuvien();
                

                DataRow dr = tbBH_PHIEU_TMP.Rows[0];
                if (dr["MAKHOHANG"] + "" == "")
                    dr["MAKHOHANG"] = Variable.ma_khohang;

                //9999
                #region "   INSERT INTO BH_PHIEU"
                string[] param = new string[] { "@flag", "@OBJID", "@DM_BAN_MA", 
                                            "@NGUOI_LAP", "@CA",//"@NGAY_GIO_VAO", "@NGAY_GIO_RA", 
                                            "@TINH_TIEN_THEO_NGAY", "@TIEN_GIO", "@THANH_TIEN", 
                                            "@CK_PHANTRAM", "@CK_TIEN", 
                                            "@VAT_PHANTRAM", "@VAT_TIEN", 
                                            "@TTIEP_PHANTRAM", "@TTIEP_TIEN", 
                                            "@PHU_THU_PHANTRAM","@PHU_THU", "@PHU_THU_KHAC", 
                                            "@TONG_TIEN", "@GHI_CHU", 
                                            "@MAKHOHANG", "@DM_THE_CODE",
                                            "@NGAY_LAM_VIEC",
                                            "@KM_PHANTRAM",
                                            "@KM_TIEN"
                                            };
                Object[] val = new Object[] { 6, dr["OBJID"], sBAN_MA,
                                            Variable.username, "ca" + Variable.username,//Variable.calamviec,//20101201
                                            lblCoTinhGio_TheoNgay.Tag, dr["TIEN_GIO"], dr["THANH_TIEN"],
                                            dr["CK_PHANTRAM"], dr["CK_TIEN"], 
                                            dr["VAT_PHANTRAM"], dr["VAT_TIEN"],
                                            dr["TTIEP_PHANTRAM"], dr["TTIEP_TIEN"],
                                            dr["PHU_THU_PHANTRAM"], dr["PHU_THU"], dr["PHU_THU_KHAC"],
                                            dr["TONG_TIEN"], dr["GHI_CHU"],
                                            Variable.ma_khohang, dr["CUSTOMER_ID"],
                                            Variable.ngay_lamviec,
                                            dr["KM_PHANTRAM"],
                                            dr["KM_TIEN"]
                                            };

                String _ioutput = "ioutput";
                othuvien.SP_Update("sp_mh_banhang_sua", param, val, ref _ioutput);
                #endregion

                #region "   INSERT INTO BH_PHIEU_CT"
                //dr["OBJID"] = _ioutput;
                if (tbBH_PHIEU_CT_TMP.GetChanges() != null)
                {//neu co thay đổi dữ liệu thì --> luu

                    foreach (DataRow _dr in tbBH_PHIEU_CT_TMP.Rows)
                    {
                        if (_dr.RowState != DataRowState.Deleted)
                        {
                            _dr["BH_PHIEU_MA"] = dr["OBJID"];
                            param = new string[] { "@flag", "@OBJID", "@BH_PHIEU_MA", 
                                        "@MAHH", "@SO_LUONG", "@DVT", 
                                        "@DON_GIA", "@CHIETKHAU_PHANTRAM", "@CHIETKHAU_TIEN", 
                                        "@VAT_PHANTRAM", "@VAT_TIEN", "@THANH_TIEN", 
                                        "@GHI_CHU", "@NGAY_TINH_GIO" };
                            val = new Object[] { 7, _dr["OBJID"], _dr["BH_PHIEU_MA"], 
                                        _dr["MAHH"], _dr["SO_LUONG"], _dr["DVT"], 
                                        _dr["DON_GIA"], _dr["CHIETKHAU_PHANTRAM"], _dr["CHIETKHAU_TIEN"],                                         
                                        _dr["VAT_PHANTRAM"], _dr["VAT_TIEN"], _dr["THANH_TIEN"], 
                                        _dr["GHI_CHU"], _dr["NGAY_TINH_GIO"]};
                            _dr["OBJID"] = othuvien.SP_Update("sp_mh_banhang_sua", param, val);

                        }
                    }
                }
                #endregion
            }
        }
        #endregion

        #region "   lblTraLai_Click"
        private void lblTraLai_Click(object sender, EventArgs e)
        {
            if (tbBH_PHIEU_CT_TMP.Rows.Count == 0) return;

            float soluongtra = 1;
            if (float.TryParse(lblCTHD_ChietKhau.Text, out soluongtra) == false)
                soluongtra = 1;

            ochon = chon.None;
            if (drBH_PHIEU_CT_TMP == null)
            {
                Mod_messagebox omessagebox = new Mod_messagebox();
                omessagebox.messagebox_pos("Thông báo", "Chọn thực đơn cần trả", 2);
            }

            else if (drBH_PHIEU_CT_TMP["OBJID"] + "" == "" || drBH_PHIEU_CT_TMP["OBJID"] + "" == "-1")
            {//remove (OBJID == NULL)

                int isoluong = int.Parse("" + drBH_PHIEU_CT_TMP["SO_LUONG"]);
                if (soluongtra > isoluong)
                {
                    Mod_messagebox omessagebox = new Mod_messagebox();
                    omessagebox.messagebox_pos("Thông báo", "Số lượng trả lớn hơn số lượng mua", 2);
                    return;
                }
                if (isoluong <= 1)
                {
                    tbBH_PHIEU_CT_TMP.Rows.Remove(drBH_PHIEU_CT_TMP);
                    drBH_PHIEU_CT_TMP = null;
                    if (ihandle > tbBH_PHIEU_CT_TMP.Rows.Count - 1)
                    {
                        --ihandle;
                        this.SetSelectRow();
                    }
                }
                else if (isoluong == soluongtra)
                {
                    tbBH_PHIEU_CT_TMP.Rows.Remove(drBH_PHIEU_CT_TMP);
                    drBH_PHIEU_CT_TMP = null;
                    if (ihandle > tbBH_PHIEU_CT_TMP.Rows.Count - 1)
                    {
                        --ihandle;
                        this.SetSelectRow();
                    }
                }
                else
                {
                    drBH_PHIEU_CT_TMP["SO_LUONG"] = isoluong - soluongtra;
                    this.RefreshCTHD(false);
                }
            }
            else
            {//remove (OBJID != NULL)

                string sMAHH = drBH_PHIEU_CT_TMP["MAHH"] + "";
                if (tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMAHH + "' AND SO_LUONG < 0").Length > 0)
                {//neu da co record SL < 0
                    DataRow dr = tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMAHH + "' AND SO_LUONG < 0")[0];
                    //string sPHAI_NHAP_LYDO_TRA_MON = Variable.tbBH_CAU_HINH.Rows[0]["PHAI_NHAP_LYDO_TRA_MON"] + "";
                    //string sGhi_Chu = "";
                    //if (sPHAI_NHAP_LYDO_TRA_MON == "True")
                    //{
                    //    mh_chu omh_chu = new mh_chu();
                    //    string sLyDoTraMon = omh_chu.ShowForm("Lý do trả món", dr["GHI_CHU"] + "", 200, 200, false);
                    //    if (omh_chu.DialogResult != DialogResult.OK)
                    //        return;
                    //    sGhi_Chu = sLyDoTraMon;
                    //}
                    //dr["GHI_CHU"] = sGhi_Chu;
                    dr["SO_LUONG"] = float.Parse("" + dr["SO_LUONG"]) - (1 * soluongtra);
                }
                else
                {//neu chua co record SL < 0 

                    string sPHAI_NHAP_LYDO_TRA_MON = Variable.tbBH_CAU_HINH.Rows[0]["PHAI_NHAP_LYDO_TRA_MON"] + "";
                    string sGhi_Chu = "";
                    if (sPHAI_NHAP_LYDO_TRA_MON == "True")
                    {
                        mh_chu omh_chu = new mh_chu();
                        string sLyDoTraMon = omh_chu.ShowForm("Lý do trả món", "", 200, 200, false);
                        if (omh_chu.DialogResult != DialogResult.OK)
                            return;
                        sGhi_Chu = sLyDoTraMon;
                    }
                    //float fCHIETKHAU_TIEN = float.Parse("0" + drBH_PHIEU_CT_TMP["CHIETKHAU_TIEN"]);
                    //float fVAT_TIEN = float.Parse("0" + drBH_PHIEU_CT_TMP["VAT_TIEN"]);
                    // tohoai _ so luong tra lai hang hoa sau khi da tam tinh



                    float fSO_LUONG = -1 * sl_giamgia;
                    DataRow dr = tbBH_PHIEU_CT_TMP.NewRow();
                    dr.ItemArray = drBH_PHIEU_CT_TMP.ItemArray;
                    dr["OBJID"] = "-1";
                    dr["COLOR"] = "2";
                    dr["SO_LUONG"] = fSO_LUONG;
                    dr["GHI_CHU"] = sGhi_Chu;
                    //dr["CHIETKHAU_TIEN"] = fCHIETKHAU_TIEN * fSO_LUONG / Math.Abs(fSO_LUONG) * -1;
                    //dr["VAT_TIEN"] = fVAT_TIEN * fSO_LUONG / Math.Abs(fSO_LUONG);
                    tbBH_PHIEU_CT_TMP.Rows.Add(dr);
                    ihandle = tbBH_PHIEU_CT_TMP.Rows.Count - 1;

                    this.SetSelectRow();
                    grdBH_PHIEU.Refresh();
                }


                this.RefreshCTHD(true);
            }
            this.Tinh_Giam_Gia_THE_VIP();
            this.TinhTongSUM();
        }
        #endregion

        #region "   lblTongCong_Click"
        private void lblTongCong_Click(object sender, EventArgs e)
        {
            //ochon = chon.TongCong;
            iLoad_TienTip = false;
            this.Load_TienTIP();
            //this.LoadVAT_AnTaiCho_MangVe();
            this.TinhTongTien();
        }
        #endregion

        #region "   lblThanhToan_Click"
        private void lblThanhToan_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                #region "   ..."
                //neu Loai_Dich_Vu nay co Tinh_Tien_Gio
                //if (tbDM_LOAIDICHVU.Rows.Count > 0)
                //    if (tbDM_LOAIDICHVU.Rows[0]["CO_TINH_TIENGIO"] + "" == "True")
                //        this.Tinh_Tien_Gio_Click();

                thuvien tv = new thuvien();
                //print_usb
                DataTable tb = tv.SP_SelectDataTable("sp_DM_MAYIN_BIENNHAN", null, null);

                object iTIEN_DA_NHAN = null;
                if (lblCTHD_VAT.Text == "" && lblCTHD_VAT1.Text != "")
                    iTIEN_DA_NHAN = lblCTHD_VAT1.Text.Replace(",", "");

                ochon = chon.None;
                //if (sMaThe_VIP != "")//
                {
                    ogiamgia_theVIP = giamgia_theVIP.None;
                    this.Tinh_Giam_Gia_THE_VIP();
                }

                this.Load_TienTIP();
                this.LoadVAT_AnTaiCho_MangVe();
                this.TinhTongTien();

                if (tbBH_PHIEU_CT_TMP.Rows.Count > 0)
                {
                    int irt = 0;
                    float iTONG_TIEN = 0;
                    string sOBJID = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
                    float.TryParse(tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"] + "", out iTONG_TIEN);

                    #region "   Kiem Tra Tien Khach dua"
                    if (iTIEN_DA_NHAN + "" != "")
                        if (int.Parse(iTIEN_DA_NHAN + "") < iTONG_TIEN)
                        {
                            int iTIEN_DAT_COC = 0;
                            string sSQL = "SELECT ISNULL((SELECT DAT_COC FROM DM_BAN_DAT_BAN WHERE BH_PHIEU_ID LIKE '" + sOBJID + "'),0)";
                            DataTable _tbDM_BAN_DAT_BAN = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
                            int.TryParse(_tbDM_BAN_DAT_BAN.Rows[0][0] + "", out iTIEN_DAT_COC);
                            if (int.Parse(iTIEN_DA_NHAN + "") + iTIEN_DAT_COC < iTONG_TIEN)
                            {
                                lblCTHD_VAT1.Text = int.Parse(iTIEN_DA_NHAN + "").ToString("N0");
                                DialogResult dlg = MessageBox_LPV.Show("Thanh toán với hình thức nợ?", MessageBox_LPV.chon.OkCancel);

                                #region "   SAVE Cong no KhachHang"
                                if (dlg == DialogResult.OK)
                                {
                                    float iSo_Tien_No = iTONG_TIEN - int.Parse(iTIEN_DA_NHAN + "") - iTIEN_DAT_COC;
                                    if (sMaThe_VIP == "" || sMaThe_VIP == "0")
                                    {
                                        mh_so omh_so = new mh_so(false, "Mã thẻ khách hàng");
                                        sMaThe_VIP = omh_so.ShowForm() + "";
                                        if (omh_so.DialogResult != DialogResult.OK || sMaThe_VIP == "")
                                            return;
                                        #region "   Kiem tra ma The co Ton_Tai?"
                                        //
                                        DataTable _tbDM_The = new thuvien().SP_SelectDataTable("sp_DM_THE",
                                                                                                new string[] { "@flag", "@CODE" },
                                                                                                new object[] { 7, sMaThe_VIP });
                                        if (_tbDM_The.Rows.Count == 0)
                                        {
                                            sMaThe_VIP = "";
                                            MessageBox_LPV.Show("Mã thẻ không tồn tại");
                                            return;
                                        }
                                        else
                                        {
                                            string ss = _tbDM_The.Rows[0][0] + "";
                                            MessageBox_LPV.Show("Khách hàng " + ss + "\nNợ " + iSo_Tien_No.ToString("N0") + "");
                                        }
                                        #endregion

                                    }

                                    //ghi cong no khach hang
                                    new thuvien().SP_Update("sp_DM_CONGNO",
                                                            new string[] { "@flag", "@MA_KHACHHANG", "@SO_PHIEU", "@DIEN_GIAI", "@THIEU_NO" },
                                                            new object[] { 1, sMaThe_VIP, sOBJID, "Khách hàng nợ", iSo_Tien_No });

                                }
                                else
                                    return;
                                #endregion

                            }
                        }
                    #endregion

                    this.lblTamTinh_Click(false);

                    #region "   1.DELETE "BH_PHIEU_TMP" INTO "BH_PHIEU""
                    sOBJID = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
                    //tbBH_PHIEU_TMP
                    irt = new thuvien().SP_Update("sp_mh_banhang_sua",
                                           new string[] { "@flag", "@OBJID", "@DM_BAN_MA", "@TIEN_DA_NHAN", "@iorder_Cho_Khach_Dat_Ban" },
                                           new object[] { 10, sOBJID, sBAN_MA, iTIEN_DA_NHAN, iorder_Cho_Khach_Dat_Ban });
                    #endregion

                    #region "   2.In RECEIPT truoc khi thoat"
                    if (lblReceipt_On.Text == "Mở in biên nhận")
                    {
                        //----------------------------------------------------------------------------------
                        DataView dv = tb.DefaultView;
                        dv.Sort = "COMNAME";
                        string sTieuDe = "";
                        // in hoa don khach san
                        if (radio_inbillkhachhang.Checked == true)
                        {
                            if (tbDM_LOAIDICHVU!=null)
                                if (tbDM_LOAIDICHVU.Rows.Count>0)
                                    if (tbDM_LOAIDICHVU.Rows[0]["OBJID"] + "" == "2")
                                    {//IN A4: TIỀN PHÒNG
                                        mh_bc_inbill_khachsan frm_bc_inbill_khachsan = new mh_bc_inbill_khachsan(sOBJID);
                                        frm_bc_inbill_khachsan.ShowDialog();
                                        goto here;
                                    }
                            
                            {
                                #region "   In BILL"
                                int vitri = dv.Find(new object[] { "USB" });
                                int vitri_bixolon = dv.Find(new object[] { "BIXOLON" });
                                int vitri_bixolon_100 = dv.Find(new object[] { "BIXOLON100" });
                                if (vitri > -1 || vitri_bixolon > -1 || vitri_bixolon_100 >-1)
                                {
                                    // in bill theo ha noi _ tieng viet
                                    mh_viewthanhtoan mh = new mh_viewthanhtoan();
                                    //if(vitri > -1 )
                                    //    mh.InBill(sOBJID, true);
                                    //else
                                    //    mh.InBill(sOBJID, false);

                                    //123
                                    if(vitri > -1 )
                                        mh.InBill(sOBJID, 1, sTieuDe,1);
                                    if (vitri_bixolon > -1)
                                        mh.InBill(sOBJID, 2, sTieuDe,1);
                                    if (vitri_bixolon_100 > -1)
                                        mh.InBill(sOBJID, 3, sTieuDe,1);

                                }
                                else
                                {
                                    print_BIEN_NHAN Oprint_BIEN_NHAN = new print_BIEN_NHAN();
                                    Oprint_BIEN_NHAN.Print_PHIEU_BIENNHAN(sOBJID);
                                }
                                #endregion
                            }
                        }
                        else
                        {
                            #region "   In BILL"
                            int vitri = dv.Find(new object[] { "USB" });
                            int vitri_bixolon = dv.Find(new object[] { "BIXOLON" });
                            int vitri_bixolon_100 = dv.Find(new object[] { "BIXOLON100" });
                            if (vitri > -1 || vitri_bixolon >  -1)
                            {
                                // in bill theo ha noi _ tieng viet
                                mh_viewthanhtoan mh = new mh_viewthanhtoan();
                                //if(vitri >-1)
                                //    mh.InBill(sOBJID, true);
                                //else
                                //    mh.InBill(sOBJID, false);

                                //123
                                if(vitri >-1)
                                    mh.InBill(sOBJID, 1, sTieuDe,1);
                                if (vitri_bixolon > -1)
                                    mh.InBill(sOBJID, 2, sTieuDe,1);
                                if (vitri_bixolon_100 > -1)
                                    mh.InBill(sOBJID, 3, sTieuDe,1);


                            }
                            else
                            {
                                print_BIEN_NHAN Oprint_BIEN_NHAN = new print_BIEN_NHAN();
                                Oprint_BIEN_NHAN.Print_PHIEU_BIENNHAN(sOBJID);
                            }
                            #endregion
                        }
                    }
                here:
                    #endregion

                    #region "   if (irt > 2 || irt == 1)"
                    if (irt > 2 || irt == 1)
                    {
                        if (iHINH_THUC_BAN_HANG == 1)//ban
                        {
                            this.DialogResult = DialogResult.OK;
                            this.Dispose();
                        }
                        else if (iHINH_THUC_BAN_HANG == 0 || iHINH_THUC_BAN_HANG == 2)//Ban & Thuc Don 
                        {
                            //this.mh_banhang_Load(null, null);//20101213
                            this.New_mh_banhang_CT();
                        }
                    }
                    #endregion

                }
                sMaThe_VIP = "";

                //iDaLoad_TienTIP = false;
                #endregion
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                MessageBox_LPV.Show("Thông báo " + DateTime.Now.ToString() + "\n" + ex.Message);
                //throw ex;
            }
            this.Cursor = Cursors.Default;
        }
        #endregion

        void New_mh_banhang_CT()
        {
            tbBH_PHIEU_CT_TMP.Rows.Clear();
            tbBH_PHIEU_TMP.Rows.Clear();
            tbDeletePhieuCT.Rows.Clear();
            //sBAN_MA = "";
            sPhieu_Ma = "";
            sKhuVucMa = "";
            sMaThe_VIP = "";
            //lblKhuVuc_Ban.Text = lblKhuVuc_Ban.Tag + "";

            this.ShowInfo();
        }

        #region "   lblCoTinhGio_TheoNgay_Click"
        private void lblCoTinhGio_TheoNgay_Click(object sender, EventArgs e)
        {
            ochon = chon.None;
            if (lblCoTinhGio_TheoNgay.Text != "")
            {
                //DialogResult dlg = LPV_POS.Module.MessageBox_LPV.Show("Đăng ký phòng ở theo?", "Thông báo", MessageBoxIcon.Question, "Ngày", "Giờ");

                ////if (lblCoTinhGio_TheoNgay.Tag + "" == "0")
                //if (dlg == DialogResult.OK)//o theo ngay
                //    tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] = 1;
                //else
                //    tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] = 0;
                mh_banhang8_HOTEL_CHON omh_banhang8_HOTEL_CHON = new mh_banhang8_HOTEL_CHON();
                int irt = omh_banhang8_HOTEL_CHON.ShowForm();
                if (omh_banhang8_HOTEL_CHON.DialogResult == DialogResult.OK)
                    tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] = irt;
                this.HienThi_oTheoNGay_Gio();

                //this.Tinh_Tien_Gio_Click();
            }
        }
        void HienThi_oTheoNGay_Gio()
        {
            lblKhuVuc_Ban.Text = "";
            
            if (tbDM_LOAIDICHVU.Rows[0]["OBJID"] + "" == "2")//Hotel
            {
                #region "   Hotel.lblKhuVuc_Ban.Text = NGAY/GIO"
                int iTheoNgay = 0;
                int.TryParse(tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] + "", out iTheoNgay);
                if (iTheoNgay == 2)
                {
                    lblCoTinhGio_TheoNgay.Tag = "2";//tinh tien theo thang
                    lblKhuVuc_Ban.Text = "Tháng ";
                }
                else if (iTheoNgay == 1)
                {
                    lblCoTinhGio_TheoNgay.Tag = "1";//tinh tien theo ngay
                    lblKhuVuc_Ban.Text = "Ngày ";
                }
                else
                {
                    //LPV_POS.Module.MessageBox_LPV.Show("Đăng ký ở theo giờ?", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    lblCoTinhGio_TheoNgay.Tag = "0";//tinh tien theo gio
                    tbBH_PHIEU_TMP.Rows[0]["TINH_TIEN_THEO_NGAY"] = 0;
                    lblKhuVuc_Ban.Text = "Giờ ";
                }
                #endregion
            }
            
            if (sMaThe_VIP != "")
            {
                #region "   THE VIP"
                string sSQL = "SELECT tenKH = ISNULL(k.OBJNAME, nk.OBJNAME) " +
                              "FROM DM_THE t " +
                              "     LEFT JOIN DM_KHACHHANG k ON k.OBJID = t.DM_KHACHHANG_MA " +
                              "     LEFT JOIN DM_NHOMKHACHHANG nk ON t.DM_NHOMKHACHHANG_MA = nk.OBJID " +
                              "WHERE T.CODE LIKE '" + sMaThe_VIP + "' ";
                DataTable tbDM_THE = new thuvien().SP_SelectDataTable("SP_EXECUTESQL",
                                                                    new string[] { "@sSQL" },
                                                                    new string[] { sSQL });
                if (tbDM_THE.Rows.Count > 0)
                    if (tbDM_THE.Rows[0]["tenKH"] + "" != "")
                    {
                        if (lblKhuVuc_Ban.Text == "")
                            lblKhuVuc_Ban.Text = tbDM_THE.Rows[0]["tenKH"] + "";
                        else
                            lblKhuVuc_Ban.Text = lblKhuVuc_Ban.Text + "(" + tbDM_THE.Rows[0]["tenKH"] + ")";
                    }
                #endregion
            }
            lblLoaiDichVu.Text = lblLoaiDichVu.Tag + "\n" + lblKhuVuc_Ban.Tag;
        }
        #endregion

        #region "   TinhTongSUM"

        void TinhTongSUM()
        {
            string sGIA_MOI_MAT_HANG_KHONG_GOM_THUE = Variable.tbBH_CAU_HINH.Rows[0]["GIA_MOI_MAT_HANG_KHONG_GOM_THUE"] + "";
            //string sTHUE_TU_CHON = Variable.tbBH_CAU_HINH.Rows[0]["THUE_TU_CHON"] + "";

            iCoVAT = (sGIA_MOI_MAT_HANG_KHONG_GOM_THUE == "True" && iCoVAT);//a

            ochon = chon.None;
            double _iThanhTien_CT = 0;
            float iSO_LUONG, iDON_GIA;

            #region "   iVAT_TIEN_ALL; iCHIETKHAU_TIEN_ALL"
            float iCHIETKHAU_TIEN;
            float iCHIETKHAU_TIEN_ALL = 0;

            float iVAT_TIEN = 0;
            float iVAT_TIEN_ALL = 0;

            if (ogiamgia_theVIP == giamgia_theVIP.hoadon_tien)
                float.TryParse(tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"] + "", out iCHIETKHAU_TIEN_ALL);

            foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Select("MAHH NOT LIKE 'Tien_Gio'"))
            {
                if (dr["MAHH"] + "" != "Tien_Gio")
                {
                    float.TryParse(dr["SO_LUONG"] + "", out iSO_LUONG);
                    float.TryParse(dr["DON_GIA"] + "", out iDON_GIA);

                    #region "   iCHIETKHAU_TIEN"
                    float.TryParse(dr["CHIETKHAU_TIEN"] + "", out iCHIETKHAU_TIEN);
                    #endregion
                    {
                        #region "   iVAT_TIEN = (iDON_GIA * iSO_LUONG - iCHIETKHAU_TIEN) * VAT_PHANTRAM"
                        if (iCoVAT)//if (dr["VAT_TIEN"] + "" != "" || dr["VAT_TIEN"] + "" != "0" || dr["VAT_TIEN"] + "" != "0.0")
                        {
                            Double dvat_TIEN = this.tinh_phantram(iDON_GIA * iSO_LUONG - iCHIETKHAU_TIEN, dr["VAT_PHANTRAM"] + "%", new Label());
                            dr["VAT_TIEN"] = dvat_TIEN;
                        }
                        else //if (!iCoVAT)
                            dr["VAT_TIEN"] = 0;
                        float.TryParse(dr["VAT_TIEN"] + "", out iVAT_TIEN);
                        //dr["THANH_TIEN"] = iSO_LUONG * iDON_GIA;// -iCHIETKHAU_TIEN + iVAT_TIEN;//20101104_bo
                        #endregion
                    }
                    #region "   iCHIETKHAU_TIEN_ALL - iVAT_TIEN_ALL"
                    if (ogiamgia_theVIP == giamgia_theVIP.hoadon_tien)
                    {
                        if (iCHIETKHAU_TIEN_ALL == 0)//chua set data vao iCHIETKHAU_TIEN_ALL (CK_TIEN)
                            iCHIETKHAU_TIEN_ALL += iCHIETKHAU_TIEN;
                        dr["CHIETKHAU_TIEN"] = 0;
                    }
                    else
                        iCHIETKHAU_TIEN_ALL += iCHIETKHAU_TIEN;
                    iVAT_TIEN_ALL += iVAT_TIEN;
                    #endregion


                }
            }
            #endregion

            //1. Thanh tien
            #region "   _iThanhTien_CT"
            double.TryParse("0" + tbBH_PHIEU_CT_TMP.Compute("SUM(THANH_TIEN)", ""), out _iThanhTien_CT);
            double _itiengio = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["TIEN_GIO"]);

            tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"] = _iThanhTien_CT;
            #endregion

            //2. CHIETKHAU_TIEN
            #region "   iCHIETKHAU_TIEN_ALL"

            tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"] = iCHIETKHAU_TIEN_ALL;
            lblHD_CK1.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"].ToString()).ToString("N0");
            double total2 = _iThanhTien_CT - iCHIETKHAU_TIEN_ALL;
            #endregion

            #region "   3.Phi dich vu"
            double iPhi_dich_Vu_tien = this.Load_TienPHI_DICH_VU(_iThanhTien_CT);
            double total3 = total2 + iPhi_dich_Vu_tien;
            #endregion

            #region "   4.Phu_Thu_Khac - Constant"
            double iPhu_Thu_Khac = 0;
            double.TryParse(tbBH_PHIEU_TMP.Rows[0]["PHU_THU_KHAC"] + "", out iPhu_Thu_Khac);
            double total4 = total3 + iPhu_Thu_Khac;
            #endregion

            #region "   5.KHUYEN MAI"
            double iKHUYEN_MAI = 0;
            double.TryParse(tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] + "", out iKHUYEN_MAI);
            double total5 = total4 - iKHUYEN_MAI;
            #endregion

            #region "   Kiem Tra VAT"
            int iVAT_TMP = 0;
            Boolean iPrintVAT = false;
            if (tbBH_PHIEU_CT_TMP.Rows.Count > 0)//neu % VAT tat ca deu = nhau thi ko in
            {
                int.TryParse(tbBH_PHIEU_CT_TMP.Rows[0]["VAT_PHANTRAM"] + "", out iVAT_TMP);
                iPrintVAT = !(tbBH_PHIEU_CT_TMP.Select("VAT_PHANTRAM=" + iVAT_TMP).Length == tbBH_PHIEU_CT_TMP.Rows.Count);
            }
            #endregion

            #region "   iVAT_return"
            ////////////////////VAT////////////////////
            double iVAT_return = 0;
            if (iCoVAT)
            {
                if (!iPrintVAT)
                {//OK//neu 
                    iVAT_return = total5 * iVAT_TMP / 100;//33,810
                }
                else
                {//kiem tra lai
                    //VAT%
                    iVAT_return = Math.Round(iVAT_TIEN_ALL / (_iThanhTien_CT - iCHIETKHAU_TIEN_ALL), 2);

                    //VAT_tien return
                    iVAT_return = total5 * iVAT_return;
                }
            }
            iVAT_return = Math.Round(iVAT_return / 100, 0) * 100;
            tbBH_PHIEU_TMP.Rows[0]["VAT_TIEN"] = iVAT_return;
            lblHD_VAT1.Text = iVAT_return.ToString("N0");
            #endregion

            //ko xai
            #region "PHU_THU - bo"
            //PHU_THU_PHANTRAM --> PHU_THU
            //double _PHU_THU = 0;
            //double.TryParse(tbBH_PHIEU_TMP.Rows[0]["PHU_THU_PHANTRAM"] + "", out _PHU_THU);//phí dịch vụ 
            //if (_PHU_THU > 0)
            //{
            //    _PHU_THU = this.tinh_phantram(_itiengio + _iThanhTien_CT, _PHU_THU + "%", lblHD_PhiDichVu);
            //    tbBH_PHIEU_TMP.Rows[0]["PHU_THU"] = _PHU_THU;//phí dịch vụ
            //}
            #endregion
        }
        #endregion

        #region "   TinhTongTien"
        void TinhTongTien()
        { //Phieu.THANH_TIEN = SUM(Phieu_CT.THANH_TIEN)
            this.TinhTongSUM();
            //lblHD_TongTien.Text = int.Parse(tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"].ToString().Replace(".0000","")).ToString("N0");
            lblCTHD_ChietKhau.Text = "TỔNG TIỀN";
            // chuong 123
            if (tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"] + "" != "")
                lblCTHD_ChietKhau1.Text = float.Parse(tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"] + "").ToString("N0");
            else
                lblCTHD_ChietKhau1.Text = "0";
            lblCTHD_VAT.Text = "";
            lblCTHD_VAT1.Text = "";
            lblCTHD_VAT1.Visible = false;
            ochon = chon.None;
        }
        #endregion

        #endregion

        #region "   CTHD"
        #region "   gridView1_CellValueChanged"
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            this.RefreshCTHD(true);
            //this.TinhTongSUM();
        }
        #endregion

        #region "   VAT"
        string VAT(string stieude)
        {
            mh_dmthueVAT omh_dmthueVAT = new mh_dmthueVAT(stieude);
            string sVAT = omh_dmthueVAT.ShowForm();
            return sVAT;
        }
        #endregion

        #region "   RefreshCTHD"
        void RefreshCTHD(Boolean isCurrentRow)
        {
            //neu co khuyen mai thi ko xai ham nay
            if (sMaThe_VIP == "")
            {
                float fSO_LUONG = 0;
                float fSO_LUONG_sub = 0;
                float fCHIETKHAU_TIEN = 0;
                float fVAT_TIEN = 0;

                if (drBH_PHIEU_CT_TMP != null)
                    foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Rows)
                    {
                        if (drBH_PHIEU_CT_TMP["MAHH"] + "" == dr["MAHH"] + "")
                        {
                            if (isCurrentRow)
                            {
                                this.Refresh_VAT_CT(drBH_PHIEU_CT_TMP);
                                float.TryParse(drBH_PHIEU_CT_TMP["SO_LUONG"] + "", out fSO_LUONG);
                                float.TryParse(drBH_PHIEU_CT_TMP["CHIETKHAU_TIEN"] + "", out fCHIETKHAU_TIEN);
                                float.TryParse(drBH_PHIEU_CT_TMP["VAT_TIEN"] + "", out fVAT_TIEN);
                            }
                            else if (fSO_LUONG == 0)
                            {
                                this.Refresh_VAT_CT(dr);
                                float.TryParse(dr["SO_LUONG"] + "", out fSO_LUONG);
                                float.TryParse(dr["CHIETKHAU_TIEN"] + "", out fCHIETKHAU_TIEN);
                                float.TryParse(dr["VAT_TIEN"] + "", out fVAT_TIEN);
                            }

                            //dr["DVT"] = drBH_PHIEU_CT_TMP["DVT"];
                            //dr["DON_GIA"] = drBH_PHIEU_CT_TMP["DON_GIA"];
                            //dr["CHIETKHAU_PHANTRAM"] = drBH_PHIEU_CT_TMP["CHIETKHAU_PHANTRAM"];
                            //dr["VAT_PHANTRAM"] = drBH_PHIEU_CT_TMP["VAT_PHANTRAM"];
                            // dr["PHU_THU_PHANTRAM"] = drBH_PHIEU_CT_TMP["PHU_THU_PHANTRAM"];

                            float.TryParse(dr["SO_LUONG"] + "", out fSO_LUONG_sub);
                            //

                            //      CK / VAT   
                            //      GIAM / TANG
                            //      + / -


                            dr["CHIETKHAU_TIEN"] = fCHIETKHAU_TIEN * fSO_LUONG / Math.Abs(fSO_LUONG) / Math.Abs(fSO_LUONG) * fSO_LUONG_sub;//chi đổi dấu, + hoặc -
                            dr["VAT_TIEN"] = fVAT_TIEN * fSO_LUONG / Math.Abs(fSO_LUONG) / Math.Abs(fSO_LUONG) * fSO_LUONG_sub;//chi đổi dấu, + hoặc -
                        }
                    }
            }
        }
        #endregion

        #region "   Refresh_VAT_CT"
        void Refresh_VAT_CT(DataRow drCTHD)
        {
            try
            {
                if (drCTHD != null)
                {
                    float fSO_LUONG = 0;
                    float.TryParse(drCTHD["SO_LUONG"] + "", out fSO_LUONG);

                    float fDON_GIA = 0;
                    float.TryParse(drCTHD["DON_GIA"] + "", out fDON_GIA);

                    float fCHIETKHAU_PHANTRAM = 0;
                    float.TryParse(drCTHD["CHIETKHAU_PHANTRAM"] + "", out fCHIETKHAU_PHANTRAM);

                    float fVAT_PHANTRAM = 0;
                    float.TryParse(drCTHD["VAT_PHANTRAM"] + "", out fVAT_PHANTRAM);

                    float fCHIETKHAU_TIEN = 0;
                    if (fCHIETKHAU_PHANTRAM != 0)
                    {
                        fCHIETKHAU_TIEN = (float)this.tinh_phantram(fSO_LUONG * fDON_GIA, drCTHD["CHIETKHAU_PHANTRAM"] + "%", new Label());
                        drCTHD["CHIETKHAU_TIEN"] = fCHIETKHAU_TIEN;
                    }

                    if (fVAT_PHANTRAM != 0)
                    {
                        double dVAT_TIEN = 0;
                        if (iCoVAT)
                            dVAT_TIEN = this.tinh_phantram(fSO_LUONG * fDON_GIA - fCHIETKHAU_TIEN, drCTHD["VAT_PHANTRAM"] + "%", new Label());
                        drCTHD["VAT_TIEN"] = dVAT_TIEN;
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion



        #region "   lblCTHD_VAT1_Click"
        private void lblCTHD_VAT1_Click(object sender, EventArgs e)
        {
            if (lblCTHD_VAT.Text != "")//neu ko phai la TINH_TONG
            {
                string sv = this.VAT("Vat");
                if (sv != "")
                {
                    double igia = 0;
                    double.TryParse(lblCTHD_ChietKhau1.Tag + "", out igia);
                    Double dVAT_TIEN = this.tinh_phantram(igia, sv, lblCTHD_VAT1);
                    drBH_PHIEU_CT_TMP["VAT_TIEN"] = dVAT_TIEN;
                    this.TinhTongSUM();
                    /////
                    if (sv.IndexOf("%") > 0 && new cpublic().IsNumeric(sv.Trim().Replace("%", "").Trim()))
                        drBH_PHIEU_CT_TMP["VAT_PHANTRAM"] = int.Parse(sv.Trim().Replace("%", "").Trim());
                    this.RefreshCTHD(true);
                }
            }
        }
        #endregion

        /// <summary>
        /// ////////hoa don
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>         
        #region "   lblHD_CK1_Click"
        private void lblHD_CK1_Click(object sender, EventArgs e)
        {
            //string sv = this.VAT("Chiết khấu");
            //if (sv != "")
            //{
            //    int itiengio = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["TIEN_GIO"]);
            //    int ithanhtien = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"]);

            //    Double dCK_TIEN = this.tinh_phantram(itiengio + ithanhtien, sv, lblHD_CK1);
            //    tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"] = dCK_TIEN;
            //    /////
            //    if (sv.IndexOf("%") > 0 && new cpublic().IsNumeric(sv.Trim().Replace("%", "").Trim()))
            //        tbBH_PHIEU_TMP.Rows[0]["CK_PHANTRAM"] = int.Parse(sv.Trim().Replace("%", "").Trim());
            //}
        }
        #endregion

        #region "   lblHD_VAT1_Click"
        private void lblHD_VAT1_Click(object sender, EventArgs e)
        {
            ochon = chon.None;
            mh_banhang6_PhuThu omh_banhang6_PhuThu = new mh_banhang6_PhuThu();
            omh_banhang6_PhuThu.ShowDialog();
            //if (omh_banhang6_PhuThu.DialogResult == DialogResult.OK)
            {
                this.Show_Apply_VAT();
                this.TinhTongSUM();
                this.gvHoaDon_CT_FocusedRowChanged(null, null);
            }
            //string sv = this.VAT("Vat");
            //if (sv != "")
            //{/////////////
            //    int itiengio = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["TIEN_GIO"]);
            //    int ithanhtien = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"]);

            //    Double dCK_TIEN = this.tinh_phantram(itiengio + ithanhtien, sv, lblHD_VAT1);
            //    tbBH_PHIEU_TMP.Rows[0]["VAT_TIEN"] = dCK_TIEN;
            //    /////
            //    if (sv.IndexOf("%") > 0 && new cpublic().IsNumeric(sv.Trim().Replace("%", "").Trim()))
            //        tbBH_PHIEU_TMP.Rows[0]["VAT_PHANTRAM"] = int.Parse(sv.Trim().Replace("%", "").Trim());
            //    this.TinhTongSUM();
            //}
        }
        #endregion

        #region "   lblHD_TIENTIEP1_Click"
        private void lblHD_TIENTIEP1_Click(object sender, EventArgs e)
        {
            //string sv = this.VAT("Tiền TIP");
            //if (sv != "")
            //{
            //    int itiengio = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["TIEN_GIO"]);
            //    int ithanhtien = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"]);

            //    Double dCK_TIEN = this.tinh_phantram(itiengio + ithanhtien, sv, lblHD_TIENTIEP1);
            //    tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"] = dCK_TIEN;
            //    /////
            //    if (sv.IndexOf("%") > 0 && new cpublic().IsNumeric(sv.Trim().Replace("%", "").Trim()))
            //        tbBH_PHIEU_TMP.Rows[0]["TTIEP_PHANTRAM"] = int.Parse(sv.Trim().Replace("%", "").Trim());
            //}
        }
        #endregion

        #region "   lblHD_PhiDichVu_Click"
        private void lblHD_PhiDichVu_Click(object sender, EventArgs e)
        {
            //string sv = this.VAT("Phí Dịch Vụ");
            //if (sv != "")
            //{
            //    int itiengio = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["TIEN_GIO"]);
            //    int ithanhtien = int.Parse("0" + tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"]);

            //    Double dCK_TIEN = this.tinh_phantram(itiengio + ithanhtien, sv, lblHD_PhiDichVu);
            //    tbBH_PHIEU_TMP.Rows[0]["PHU_THU"] = dCK_TIEN;//phí dịch vụ

            //    if (sv.IndexOf("%") > 0 && new cpublic().IsNumeric(sv.Trim().Replace("%", "").Trim()))
            //        tbBH_PHIEU_TMP.Rows[0]["PHU_THU_PHANTRAM"] = int.Parse(sv.Trim().Replace("%", "").Trim());
            //    this.TinhTongSUM();
            //}
        }
        #endregion

        #region "   tinh_phantram"
        Double tinh_phantram(Double _ThanhTien, string phantram, Label lblXemGiaTri)
        {//tinh cho ca CHIET_KHAU va VAT
            Double db = 0;
            try
            {
                if (phantram.IndexOf("%") > 0)
                {
                    db = Double.Parse("0" + phantram.Replace("%", ""));
                    db = Math.Round(_ThanhTien * db / 100f / 100, 0) * 100;//lam tron 2 so (123,123.45 --> 123,100)
                }
                else if (new cpublic().IsNumeric(phantram))
                    Double.TryParse(phantram, out db);
                lblXemGiaTri.Text = db.ToString("N0");
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            return db;
        }
        #endregion

        #endregion

        #region "   lblInLai_HoaDon_Click"
        private void lblInLai_HoaDon_Click(object sender, EventArgs e)
        {
            ochon = chon.None;
            if (Variable.username == "") return;
            new LPV_POS.In.Print_InLai_HoaDon(sKhuVucMa).ShowDialog();
        }
        #endregion

        #region "   Bàn phim NUMLOCK................................."
        private void lblnum_tru_Click(object sender, EventArgs e)
        {
            try
            {
                if (drBH_PHIEU_CT_TMP != null)
                {
                ll:
                    string sMaHH = drBH_PHIEU_CT_TMP["MAHH"] + "";
                    string sOBJID = drBH_PHIEU_CT_TMP["OBJID"] + "";
                ll2:
                    if (sMaHH != "Tien_Gio")
                    {
                        if ((sOBJID == "-1" || sOBJID == ""))
                        {//sOBJID == ""
                            float soluong = 0.0f;
                            float.TryParse(drBH_PHIEU_CT_TMP["SO_LUONG"] + "", out soluong);

                            float don_gia = 0.0f;
                            float.TryParse(drBH_PHIEU_CT_TMP["DON_GIA"] + "", out don_gia);

                            if (soluong <= 1 && soluong > 0)
                            {
                                this.lblxoa_ThucDon_Click(null, null);
                                soluong = 0;
                            }
                            else
                            {
                                string sGhiChu = "";
                                string sPHAI_NHAP_LYDO_TRA_MON = Variable.tbBH_CAU_HINH.Rows[0]["PHAI_NHAP_LYDO_TRA_MON"] + "";
                                if (sPHAI_NHAP_LYDO_TRA_MON == "True")
                                {
                                    mh_chu omh_chu = new mh_chu();
                                    string sLyDoTraMon = omh_chu.ShowForm("Lý do trả món", drBH_PHIEU_CT_TMP["GHI_CHU"] + "", 200, 200, false);
                                    if (omh_chu.DialogResult != DialogResult.OK)
                                        return;
                                    sGhiChu = sLyDoTraMon;
                                }
                                drBH_PHIEU_CT_TMP["GHI_CHU"] = sGhiChu;
                                //drBH_PHIEU_CT_TMP["OBJNAME_HH"] = "" + drBH_PHIEU_CT_TMP["OBJNAME_HH_root"];
                                //DataRow dr =
                                this.Add_DataRow_tbDeletePhieuCT(drBH_PHIEU_CT_TMP, drBH_PHIEU_CT_TMP["SO_LUONG"]);//20101019

                                drBH_PHIEU_CT_TMP["SO_LUONG"] = --soluong;
                            }
                            grdBH_PHIEU.Refresh();
                            this.Update_SOLUONG_TMP(sMaHH, int.Parse("" + soluong), don_gia, drBH_PHIEU_CT_TMP["DVT"] + "");

                        }
                        else if (sOBJID != "-1")
                        {
                            sOBJID = "-1";
                            if (tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHH + "' AND (OBJID IS NULL OR OBJID = -1)").Length > 0)
                            {
                                for (ihandle = 0; ihandle < tbBH_PHIEU_CT_TMP.Rows.Count; ihandle++)
                                    if (tbBH_PHIEU_CT_TMP.Rows[ihandle]["OBJID"] + "" == sOBJID)
                                        goto rd20101013;
                            rd20101013:
                                drBH_PHIEU_CT_TMP = tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHH + "' AND (OBJID IS NULL OR OBJID = -1)")[0];

                                this.SetSelectRow();

                                goto ll;
                            }
                            goto ll2;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }

        private void lblnum_cong_Click(object sender, EventArgs e)
        {
            if (drBH_PHIEU_CT_TMP != null)
            {
                try
                {
                    string sMaHH = drBH_PHIEU_CT_TMP["MAHH"] + "";
                    if (sMaHH != "Tien_Gio")
                    {
                        //if (drBH_PHIEU_CT_TMP["OBJID"] + "" == "")
                        {
                            //this.Update_SOLUONG_TMP(drBH_PHIEU_CT_TMP["MAHH"] + "", int.Parse("" + soluong));
                            this.Insert2TableCT("", sMaHH,
                                                drBH_PHIEU_CT_TMP["OBJNAME_HH_root"] + "",
                                                int.Parse("0" + drBH_PHIEU_CT_TMP["DON_GIA"]),
                                                1,
                                                drBH_PHIEU_CT_TMP["DVT"] + "",
                                                int.Parse("0" + drBH_PHIEU_CT_TMP["CHIETKHAU_PHANTRAM"]),
                                                drBH_PHIEU_CT_TMP["DM_MAYIN_BEP_MA"] + "", drBH_PHIEU_CT_TMP["VAT_PHANTRAM"]);
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                }
            }
            new Mod_messagebox().messagebox_pos("Thông báo", "Không thể thay đổi dữ liệu", 2);
        }

        private void lblnum_nhan_Click(object sender, EventArgs e)
        {
            if (drBH_PHIEU_CT_TMP != null)
            {
                float iDon_Gia = 0;
                float.TryParse(drBH_PHIEU_CT_TMP["DON_GIA"] + "", out iDon_Gia);

                if (drBH_PHIEU_CT_TMP["OBJID"] + "" != "-1" || drBH_PHIEU_CT_TMP["MAHH"] + "" == "Tien_Gio")
                {
                    new Mod_messagebox().messagebox_pos("Thông báo", "Không thể thay đổi số lượng.", 2);
                    return;
                }

                float so_luong = 0;
                if (new cpublic().IsNumeric(lblCTHD_ChietKhau.Text))
                {//So --> so_luong
                    float.TryParse(lblCTHD_ChietKhau.Text, out so_luong);
                    drBH_PHIEU_CT_TMP["SO_LUONG"] = so_luong;
                    grdBH_PHIEU.Refresh();
                    this.lblnum_clr_Click(null, null);
                }
                else
                {//mh_so --> so_luong
                    string sss = new cpublic().loadformso_point(600, 200);
                    //new mh_so().ShowDialog();
                    if (new cpublic().IsNumeric(Variable.str_so))
                    {
                        so_luong = float.Parse(Variable.str_so);
                        drBH_PHIEU_CT_TMP["SO_LUONG"] = so_luong;
                        grdBH_PHIEU.Refresh();
                        this.lblnum_clr_Click(null, null);
                    }
                }
                so_luong = so_luong / 2 * 2;
                this.Update_SOLUONG_TMP(drBH_PHIEU_CT_TMP["MAHH"] + "", int.Parse("" + so_luong), iDon_Gia, drBH_PHIEU_CT_TMP["DVT"] + "");
            }
        }

        private void lblnum_clr_Click(object sender, EventArgs e)
        {
            this.gvHoaDon_CT_FocusedRowChanged(null, null);
        }

        private void lblnum_0_Click(object sender, EventArgs e)
        {
            if (lblCTHD_VAT.Text == "")
            {
                float iGiaTri = 0;
                lblCTHD_VAT1.Text += ((System.Windows.Forms.Control)sender).Tag + "";
                float.TryParse(lblCTHD_VAT1.Text.Replace(",", ""), out iGiaTri);


                lblCTHD_VAT1.Text = iGiaTri.ToString("N0");
                lblCTHD_VAT1.Visible = true;
            }
            else
            {
                this.ClearlblNum_Click();
                lblCTHD_ChietKhau.Text += ((System.Windows.Forms.Control)sender).Tag + "";
                float.TryParse(lblCTHD_ChietKhau.Text.Replace(",", ""), out sl_giamgia);
                return;
            }
        }

        private void lblnum_enter_Click(object sender, EventArgs e)
        {
            if (new cpublic().IsNumeric(lblCTHD_ChietKhau.Text))
            {
                //string sSQL = "SELECT dh.OBJID, dh.OBJNAME, dh.GIA1, MADVT " +
                //              "     , khuyenmai_phantram = (SELECT dbo.fnc_KhuyenMai_HangHoa('" + Variable.ma_khohang + "', dh.OBJID, GETDATE(), '" + sMaThe_VIP + "')) " +
                //              "     , dn2.DM_MAYIN_BEP_MA " +
                //              "FROM DM_HH dh " +
                //                "LEFT JOIN DM_NHOMHH dn ON dn.OBJID = dh.MANHOMHH " +
                //                "LEFT JOIN DM_NHOMCHUHH dn2 ON dn.MANHOMCHU = dn2.OBJID " +
                //                "LEFT JOIN DM_MAYIN_BEP dmb ON dn2.DM_MAYIN_BEP_MA = dmb.DM_MAYIN_BEP_MA " +
                //              "WHERE dh.SHORTID = " + lblCTHD_ChietKhau.Text + " ";

                //DataTable DM_HH = new thuvien().SP_SelectDataTable("sp_executesql", new string[] { "@sSQL" }, new object[] { sSQL });
                string _sMA_NHOM_HH = gvNhom_Mon.GetDataRow(gvNhom_Mon.FocusedRowHandle)["OBJID"] + "";
                DataTable DM_HH = new thuvien().SP_SelectDataTable("sp_mh_banhang_sua",
                                                                new string[] { "@MANHOMHH", "@flag", "@MAKHOHANG", "@thang_nam", "@DM_THE_CODE", "@SHORTID" },
                                                                new object[] { _sMA_NHOM_HH, 3, Variable.ma_khohang, timer1.Tag, sMaThe_VIP, lblCTHD_ChietKhau.Text });
                if (DM_HH.Rows.Count > 0)
                {
                    string _maHH = "";
                    string _tenHH = "";
                    string _MADVT = "";
                    int _dongia = 0;
                    int _khuyenmai_phantram = 0;
                    _maHH = DM_HH.Rows[0]["OBJID"] + "";
                    _tenHH = DM_HH.Rows[0]["OBJNAME"] + "";
                    string sGia = DM_HH.Rows[0]["GIA1"] + "";
                    _MADVT = DM_HH.Rows[0]["MADVT"] + "";
                    int.TryParse(sGia.Replace(".0000", ""), out _dongia);
                    int.TryParse(DM_HH.Rows[0]["khuyenmai_phantram"] + "", out _khuyenmai_phantram);
                    string _DM_MAYIN_BEP_MA = DM_HH.Rows[0]["DM_MAYIN_BEP_MA"] + "";
                    object ivat_phantram = DM_HH.Rows[0]["Vat"] + "";

                    this.gvHoaDon_CT_FocusedRowChanged(null, null);
                    this.Insert2TableCT("", _maHH, _tenHH, _dongia, 1, _MADVT, _khuyenmai_phantram, _DM_MAYIN_BEP_MA, ivat_phantram);
                }
            }
            else
            {
            }
        }

        #region
        void ClearlblNum_Click()
        {
            if (!new cpublic().IsNumeric(lblCTHD_ChietKhau.Text))
            {
                lblCTHD_ChietKhau.Text = "";
                lblCTHD_ChietKhau1.Visible = false;
            }
        }
        #endregion

        #endregion

        #region "   mh_banhang_CT_FormClosing"
        private void mh_banhang_CT_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (sPhieu_Ma != "")
            {
                string sSQL = "DELETE FROM BH_PHIEU_CT_SOLUONG_TMP WHERE BH_PHIEU_MA LIKE '" + sPhieu_Ma + "'";
                int irt = new thuvien().SP_Update("SP_EXECUTESQL",
                                                    new string[] { "@sSQL" },
                                                    new object[] { sSQL });
                sPhieu_Ma = "";
            }
        }
        #endregion

        #region "   mh_banhang_CT_FormClosed"
        private void mh_banhang_CT_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (sPhieu_Ma != "")
            {
                string sSQL = "DELETE FROM BH_PHIEU_CT_SOLUONG_TMP WHERE BH_PHIEU_MA LIKE '" + sPhieu_Ma + "'";
                int irt = new thuvien().SP_Update("SP_EXECUTESQL",
                                                    new string[] { "@sSQL" },
                                                    new object[] { sSQL });
                sPhieu_Ma = "";
            }
        }
        #endregion

        #region "   lblDVT_Click"
        private void lblDVT_Click(object sender, EventArgs e)
        {
            ochon = chon.None;
            if (drBH_PHIEU_CT_TMP != null)
            {
                if (tbBH_PHIEU_CT_TMP.Rows.Count == 0) return;
                string sMAHH = drBH_PHIEU_CT_TMP["MAHH"] + "";
                if (sMAHH != "Tien_Gio")
                {
                    string sten = drBH_PHIEU_CT_TMP["OBJNAME_HH_root"] + "";
                    if (sten == "")
                    {
                        sten = drBH_PHIEU_CT_TMP["OBJNAME_HH"] + "";
                    }
                    mh_banhang4_DVT omh_banhang4_DVT = new mh_banhang4_DVT(sMAHH, sten);
                    DataRow drDVT = omh_banhang4_DVT.ShowForm();
                    if (omh_banhang4_DVT.DialogResult == DialogResult.OK && drDVT != null)
                    {
                        drBH_PHIEU_CT_TMP["DVT"] = drDVT["DVT_LAST"];
                        drBH_PHIEU_CT_TMP["DON_GIA"] = drDVT["DONGIA"];

                        this.Update_SOLUONG_TMP(sMAHH, float.Parse(drBH_PHIEU_CT_TMP["SO_LUONG"] + ""), float.Parse(drDVT["DONGIA"] + ""), drDVT["DVT_LAST"] + "");
                        this.grdBH_PHIEU.Refresh();
                        this.TinhTongSUM();
                        //this.gvNhom_Mon_FocusedRowChanged(null, null);
                        this.Load_TonKHO_1Mon(sMAHH);//20101214
                    }
                }
            }
        }
        #endregion

        #region "   SetSelectRow"
        void SetSelectRow()
        {
            gvHoaDon_CT.FocusedRowHandle = ihandle;
            gvHoaDon_CT.SelectRow(ihandle);
        }
        #endregion

        #region "   lblBill_On_Click"
        private void lblBill_On_Click(object sender, EventArgs e)
        {
            if (lblBill_On.Text == "Mở in hóa đơn")
                lblBill_On.Text = "Tắt in hóa đơn";
            else
                lblBill_On.Text = "Mở in hóa đơn";
            new cpublic().Registry_Set(this.Name + lblBill_On.Name, lblBill_On.Text);
        }
        #endregion

        #region "   lblReceipt_On_Click"
        private void lblReceipt_On_Click(object sender, EventArgs e)
        {
            if (lblReceipt_On.Text == "Mở in biên nhận")
                lblReceipt_On.Text = "Tắt in biên nhận";
            else
                lblReceipt_On.Text = "Mở in biên nhận";
            new cpublic().Registry_Set(this.Name + lblReceipt_On.Name, lblReceipt_On.Text);
        }
        #endregion

        #region "   lblMenhGia_ThanhToan_Click"
        private void lblMenhGia_ThanhToan_Click(object sender, EventArgs e)
        {
            ochon = chon.MenhGia;
            try
            {
                lblTongCong_Click(null, null);
                mh_banhang5_MenhGia_ThanhToan omh_banhang5_MenhGia_ThanhToan = new mh_banhang5_MenhGia_ThanhToan();
                decimal.TryParse(lblCTHD_ChietKhau1.Text, out omh_banhang5_MenhGia_ThanhToan.m_tongtien);
                //omh_banhang5_MenhGia_ThanhToan.m_tongtien =  lblCTHD_ChietKhau1.Text;
                int iGiaTri = omh_banhang5_MenhGia_ThanhToan.ShowForm();
                if (omh_banhang5_MenhGia_ThanhToan.DialogResult == DialogResult.OK)
                {
                    //MessageBox.Show(iGiaTri.ToString("N0"), "Tiền", MessageBoxButtons.OK);
                    this.lblTongCong_Click(null, null);
                    lblCTHD_VAT1.Text = iGiaTri.ToString("N0");
                    lblCTHD_VAT1.Visible = true;
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            finally
            {
                ochon = chon.None;
            }
        }
        #endregion

        #region "   lblThanhToan_MouseDown"
        private void lblThanhToan_MouseDown(object sender, MouseEventArgs e)
        {
            lblThanhToan.BackColor = System.Drawing.Color.FromArgb(140, 215, 45);
            lblThanhToan.BorderStyle = BorderStyle.Fixed3D;
        }
        #endregion

        #region "   lblThanhToan_MouseUp"
        private void lblThanhToan_MouseUp(object sender, MouseEventArgs e)
        {
            lblThanhToan.BackColor = System.Drawing.Color.SandyBrown;
            lblThanhToan.BorderStyle = BorderStyle.FixedSingle;
        }
        #endregion

        #region "   btnColor_Click"
        private void btnColor_Click(object sender, EventArgs e)
        {//lblTamTinh

        }
        #endregion

        #region "   btnColor_Load_Click"
        private void btnColor_Load_Click(object sender, EventArgs e)
        {//lblTamTinh

        }
        #endregion

        #region "   Load_BanHang"
        void Load_BanHang()
        {
            cpublic ocpublic = new cpublic();
            foreach (System.Windows.Forms.Control ctrl in panel_BanHang.Controls)
                ocpublic.loadControl_FontColor("menufunction" + ctrl.Name, ctrl);
        }
        #endregion

        #region "   lblNhomHH_TrangTren_Click"
        private void lblNhomHH_TrangTren_Click(object sender, EventArgs e)
        {
            //this.Cursor = Cursors.WaitCursor;
            try
            {
                this.ShowDM_NHOMHH(ChonTrang.TrangTren);
            }
            catch
            {
            }
            finally
            {
                //this.Cursor = Cursors.Default;
            }
        }
        #endregion

        #region "   lblNhomHH_TrangDuoi_Click"
        private void lblNhomHH_TrangDuoi_Click(object sender, EventArgs e)
        {
            //this.Cursor = Cursors.WaitCursor;
            try
            {
                this.ShowDM_NHOMHH(ChonTrang.TrangDuoi);
            }
            catch
            {
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        #endregion

        #region "   ChonTrang"
        enum ChonTrang
        {
            None,
            TrangTren,
            TrangDuoi
        }
        #endregion

        #region "   ShowDM_NHOMHH"
        void ShowDM_NHOMHH(ChonTrang _ChonTrang)
        {

            int iTrang = 1;
            if (_ChonTrang == ChonTrang.None)
            { //FormLoad
                string _trang = new cpublic().Registry_Get(this.Name + grdDM_NHOMHH.Name + "DefaultItem") + "";
                if (new cpublic().IsNumeric(_trang))
                    iTrang = int.Parse(_trang);
            }
            else
            {
                int.TryParse(lblNhomHH_TrangTren.Tag + "", out iTrang);
                if (_ChonTrang == ChonTrang.TrangTren && iTrang > 1)
                    iTrang--;
                else if (_ChonTrang == ChonTrang.TrangDuoi && grdDM_NHOMHH.DefaultView.RowCount >= 14)
                    iTrang++;
                else if (gvNhom_Mon.RowCount > 0)
                    return;
            }
            string sSQL = "";


            int imin = 1 + (iTrang - 1) * 14;
            int imax = iTrang * 14;//1 trang có 14 dòng

            sSQL = "SELECT STT = aa.STT%4, SAPXEP = aa.STT, " +
                   "	aa.OBJID, aa.OBJNAME, aa.MANHOMCHU, aa.VAT, aa.TRANGTHAI, " +
                   "    MAX = " + iTrang + " * 14 " +
                   "FROM " +
                   "( " +
                   "	SELECT ((ROW_NUMBER() OVER (ORDER BY SAPXEP))) AS STT, " +
                   "		  OBJID, OBJNAME = UPPER(OBJNAME), MANHOMCHU, VAT, TRANGTHAI " +
                   "	FROM DM_NHOMHH " +
                   ") aa " +
                   "WHERE aa.STT >= " + imin + " " +
                   "	AND aa.STT <= " + imax + " ";

            DataTable tbDM_NHOMHH = new thuvien().SP_SelectDataTable("SP_EXECUTESQL",
                                                                    new string[] { "@sql" },
                                                                    new object[] { sSQL });
            if (tbDM_NHOMHH.Rows.Count > 0)
            {
                new cpublic().Registry_Set(this.Name + grdDM_NHOMHH.Name + "DefaultItem", iTrang);
                lblNhomHH_TrangTren.Tag = iTrang;
                grdDM_NHOMHH.DataSource = tbDM_NHOMHH;
                if (_ChonTrang != ChonTrang.None)
                    this.gvNhom_Mon_FocusedRowChanged(null, null);
            }
            else if (grdDM_NHOMHH.DataSource == null)
                grdDM_NHOMHH.DataSource = tbDM_NHOMHH;
        }
        #endregion

        #region "   Load Tien TIP"
        //Boolean iDaLoad_TienTIP = false;
        void Load_TienTIP()
        {
            //if (iDaLoad_TienTIP == true)
            //    return;
            #region "   iLoad_TienTip"
            if (!iLoad_TienTip)
            {
                string iTienTip = "0";
                try
                {
                    string sTIEN_TIP = Variable.tbBH_CAU_HINH.Rows[0]["TIEN_TIP"] + "";
                    string sTIEN_TIP_TUYCHON = Variable.tbBH_CAU_HINH.Rows[0]["TIEN_TIP_TUYCHON"] + "";
                    string sTIEN_TIP_VAT = Variable.tbBH_CAU_HINH.Rows[0]["TIEN_TIP_VAT"] + "";
                    string sTIEN_TIP_VAT_PHANTRAM = Variable.tbBH_CAU_HINH.Rows[0]["TIEN_TIP_VAT_PHANTRAM"] + "";
                    if (sTIEN_TIP == "True")
                    {
                        if (sTIEN_TIP_TUYCHON == "True")
                        {
                            int _iTTIEP_PHANTRAM = 0;
                            int _iTTIEP_TIEN = 0;
                            int.TryParse(tbBH_PHIEU_TMP.Rows[0]["TTIEP_PHANTRAM"] + "", out _iTTIEP_PHANTRAM);
                            int.TryParse(tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"] + "", out _iTTIEP_TIEN);
                            if (_iTTIEP_PHANTRAM > 0)
                                _iTTIEP_TIEN = _iTTIEP_PHANTRAM;


                            mh_so_Ban_Gia_Mo omh_so_Ban_Gia_Mo = null;
                            if (_iTTIEP_PHANTRAM > 0)
                                omh_so_Ban_Gia_Mo = new mh_so_Ban_Gia_Mo("Tiền TIP", _iTTIEP_PHANTRAM + "", "%", mh_so_Ban_Gia_Mo.Chon.Phan_Tram);
                            else
                                omh_so_Ban_Gia_Mo = new mh_so_Ban_Gia_Mo("Tiền TIP", _iTTIEP_TIEN + "", "%", mh_so_Ban_Gia_Mo.Chon.Tien);

                            string sTT = omh_so_Ban_Gia_Mo.ShowForm() + "";
                            if (omh_so_Ban_Gia_Mo.DialogResult == DialogResult.OK && sTT != "")
                            {
                                iTienTip = sTT;
                                if (iTienTip.IndexOf("%") > 0)
                                {
                                    tbBH_PHIEU_TMP.Rows[0]["TTIEP_PHANTRAM"] = iTienTip.Replace("%", "");
                                    tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"] = 0;
                                }
                                else if (new cpublic().IsNumeric(iTienTip))
                                {
                                    tbBH_PHIEU_TMP.Rows[0]["TTIEP_PHANTRAM"] = 0;
                                    tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"] = iTienTip;
                                    goto here;
                                }
                                iLoad_TienTip = true;
                            }
                        }
                        else if (sTIEN_TIP_VAT == "True" && sTIEN_TIP_VAT_PHANTRAM != "")
                        {
                            iTienTip = sTIEN_TIP_VAT_PHANTRAM + "%";
                            tbBH_PHIEU_TMP.Rows[0]["TTIEP_PHANTRAM"] = iTienTip.Replace("%", "");
                            tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"] = 0;
                            iLoad_TienTip = true;
                        }

                        if (iLoad_TienTip)
                        {
                            double _TTIEP = 0;
                            double.TryParse(tbBH_PHIEU_TMP.Rows[0]["TTIEP_PHANTRAM"] + "", out _TTIEP);
                            {
                                _TTIEP = this.tinh_phantram((double)tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"], _TTIEP + "%", lblHD_TIENTIEP1);
                                tbBH_PHIEU_TMP.Rows[0]["TTIEP_TIEN"] = _TTIEP;
                            }
                        }
                    here:
                        iTienTip = iTienTip + "";
                    }
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                }
            }
            #endregion

            //iDaLoad_TienTIP = true;
        }
        #endregion

        #region "   Load_TienPHI_DICH_VU"
        double Load_TienPHI_DICH_VU(double _iTHANH_TIEN)
        {//tinh sau khi co tong_tien_1
            #region "   sPHI_DICH_VU"
            string sPHI_DICH_VU = Variable.tbBH_CAU_HINH.Rows[0]["PHI_DICH_VU"] + "";
            double iPHI_DICH_VU_PHANTRAM = 0;
            double iPHI_DICH_VU_TIEN = 0;
            double.TryParse(Variable.tbBH_CAU_HINH.Rows[0]["PHI_DICH_VU_PHANTRAM"] + "", out iPHI_DICH_VU_PHANTRAM);
            if (sPHI_DICH_VU == "True")
            {
                tbBH_PHIEU_TMP.Rows[0]["PHU_THU_PHANTRAM"] = iPHI_DICH_VU_PHANTRAM;
                double iCK_tien = 0;
                double.TryParse(tbBH_PHIEU_TMP.Rows[0]["CK_tien"] + "", out iCK_tien);
                _iTHANH_TIEN = _iTHANH_TIEN - iCK_tien;
                iPHI_DICH_VU_TIEN = this.tinh_phantram(_iTHANH_TIEN, iPHI_DICH_VU_PHANTRAM + "%", lblHD_PhiDichVu);
                tbBH_PHIEU_TMP.Rows[0]["PHU_THU"] = iPHI_DICH_VU_TIEN;//iPHI_DICH_VU_TIEN
                iPHI_DICH_VU_TIEN = Math.Round(iPHI_DICH_VU_TIEN / 100, 0) * 100;
                lblHD_PhiDichVu.Text = iPHI_DICH_VU_TIEN.ToString("N0");
                return iPHI_DICH_VU_TIEN;
            }
            else
            {
                tbBH_PHIEU_TMP.Rows[0]["PHU_THU_PHANTRAM"] = 0;
                tbBH_PHIEU_TMP.Rows[0]["PHU_THU"] = 0;
                lblHD_PhiDichVu.Text = "0";
                return 0;
            }
            #endregion
        }
        #endregion

        #region "   LoadVAT_AnTaiCho_MangVe"
        void LoadVAT_AnTaiCho_MangVe()
        {
            if (!iLoad_VAT)
            {

                string sGIA_MOI_MAT_HANG_KHONG_GOM_THUE = Variable.tbBH_CAU_HINH.Rows[0]["GIA_MOI_MAT_HANG_KHONG_GOM_THUE"] + "";
                string sTHUE_APDUNG = Variable.tbBH_CAU_HINH.Rows[0]["THUE_APDUNG"] + "";
                string sTHUE_TU_CHON = Variable.tbBH_CAU_HINH.Rows[0]["THUE_TU_CHON"] + "";

                if (sGIA_MOI_MAT_HANG_KHONG_GOM_THUE == "True" && (sTHUE_APDUNG == "True" || sTHUE_TU_CHON == "True"))
                {
                    float ivat = 0;
                    if (sTHUE_APDUNG == "True")
                    {
                        mh_banhang6_VAT_InOut omh_banhang6_VAT_InOut = new mh_banhang6_VAT_InOut();
                        omh_banhang6_VAT_InOut.ShowDialog();
                        if (omh_banhang6_VAT_InOut.DialogResult == DialogResult.OK)
                        {//An tai cho 
                            ivat = float.Parse(Variable.tbBH_CAU_HINH.Rows[0]["THUE_AN_TAI_CHO"] + "");
                        }
                        else
                        { //Mang ve
                            ivat = float.Parse(Variable.tbBH_CAU_HINH.Rows[0]["THUE_MANG_VE"] + "");
                        }
                    }
                    else if (sTHUE_TU_CHON == "True")
                    {
                        ivat = float.Parse(Variable.tbBH_CAU_HINH.Rows[0]["VAT_MAC_DINH"] + "");
                    }
                    //float iVAT_TIEN = 0;
                    foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Select("MAHH <> 'Tien_Gio'"))
                    {
                        //iVAT_TIEN =  this.tinh_phantram((double)dr["THANH_TIEN"], ivat, new Label());
                        dr["VAT_PHANTRAM"] = ivat;
                        //this.tinh_phantram
                    }
                }
                iLoad_VAT = true;
            }
        }
        #endregion

        #region "   Tinh_Giam_Gia_THE_VIP"
        void Tinh_Giam_Gia_THE_VIP()
        {

            sMaThe_VIP = sMaThe_VIP + "";

            //HINHTHUC_KM, K.THAMSO_1, K.THAMSO_2, MAHHBAN
            DataTable tbKhuyenMai_HangHoa = new thuvien().SP_SelectDataTable("SP_DM_KHUYENMAI",
                                                                            new string[] { "@flag", "@MAKHOHANG", "@DM_THE_CODE" },
                                                                            new object[] { 1, Variable.ma_khohang, sMaThe_VIP });

            if (tbKhuyenMai_HangHoa.Rows.Count == 0)//neu ko co khuyen mai thi RETURN 
                return;

            string sDM_KHUYENMAI_MA = tbKhuyenMai_HangHoa.Rows[0]["DM_KHUYENMAI_MA"] + "";
            //THAMSO_2: so tien gioi han MIN bat buoc de dc tinh khuyen mai
            float _ithanh_tienBILL = 0;
            float _ithanh_tienKHUYENMAI = 0;//nếu tiến BILL > tienKM bắt buộc
            float.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_2"] + "", out _ithanh_tienKHUYENMAI);

            //
            //kiem tra giam_gia theo SO_LUONG hay TONG_TIEN            
            string _sHINHTHUC_KM = "";
            _sHINHTHUC_KM = tbKhuyenMai_HangHoa.Rows[0]["HINHTHUC_KM"] + "";
            if (_sHINHTHUC_KM != "11" && _sHINHTHUC_KM != "12")
            {
                //neu co
                int _iKhuyenmai_GiaTri = 0;
                #region "   foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Rows)"
                foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Rows)
                {
                    if (tbKhuyenMai_HangHoa.Select("MAHHBAN = '" + dr["MAHH"] + "'").Length > 0)
                    {
                        _ithanh_tienBILL += float.Parse(dr["THANH_TIEN"] + "");
                        _iKhuyenmai_GiaTri = int.Parse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_1"] + "");
                    }
                }
                #endregion

                //neu tien_BILL >= so tien quy dinh thi moi dc khuyenmai
                if (_ithanh_tienBILL >= _ithanh_tienKHUYENMAI)
                {
                    #region "   _sHINHTHUC_KM==2...7"
                    if (_sHINHTHUC_KM == "2")
                    {//
                        ogiamgia_theVIP = giamgia_theVIP.hoadon_tien;
                        #region "BILL_Tien"
                        foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Rows)
                        {
                            dr["KM_PHANTRAM"] = 0;
                            dr["KM_TIEN"] = _iKhuyenmai_GiaTri;
                        }
                        #endregion
                    }
                    else if (_sHINHTHUC_KM == "3")//giam % tren BILL ko can THE_KH --y/c ngay 09.02.2011
                    {// -- KM_PHANTRAM
                        #region "BILL_%"
                        int iDON_GIA = 0;
                        float iSO_LUONG = 0;
                        foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Rows)
                        {
                            dr["KM_PHANTRAM"] = _iKhuyenmai_GiaTri;

                            iDON_GIA = int.Parse(dr["DON_GIA"] + "");
                            iSO_LUONG = int.Parse(dr["SO_LUONG"] + "");
                            Double dKM_TIEN = this.tinh_phantram(iDON_GIA * iSO_LUONG, dr["KM_PHANTRAM"] + "%", new Label());
                            dr["KM_TIEN"] = dKM_TIEN;
                        }
                        #endregion
                        ogiamgia_theVIP = giamgia_theVIP.hoadon_phantram;
                    }
                    else if (_sHINHTHUC_KM == "4")
                    {
                        #region "MonReNhat_Tien"
                        DataRow drMIN = null;
                        int igiaTMP = 0;
                        foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Rows)
                        {
                            if (tbKhuyenMai_HangHoa.Select("MAHHBAN = '" + dr["MAHH"] + "'").Length > 0)
                            {//neu MON HANG co trong DS khuyen mai
                                if (igiaTMP == 0)
                                {
                                    igiaTMP = int.Parse(dr["DON_GIA"] + "");
                                    drMIN = dr;
                                }
                                else if (igiaTMP > int.Parse(dr["DON_GIA"] + ""))
                                {
                                    igiaTMP = int.Parse(dr["DON_GIA"] + "");
                                    drMIN = dr;
                                }
                            }
                            dr["KM_PHANTRAM"] = 0;
                            dr["KM_TIEN"] = 0;
                        }
                        drMIN["KM_PHANTRAM"] = 0;
                        drMIN["KM_TIEN"] = _iKhuyenmai_GiaTri;
                        #endregion
                        //ogiamgia_theVIP = giamgia_theVIP.mon_renhat_tien;
                    }
                    else if (_sHINHTHUC_KM == "5")
                    {
                        #region "MonReNhat_%"
                        DataRow drMIN = null;
                        int igiaTMP = 0;
                        foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Rows)
                        {
                            if (tbKhuyenMai_HangHoa.Select("MAHHBAN = '" + dr["MAHH"] + "'").Length > 0)
                            {//neu MON HANG co trong DS khuyen mai
                                if (igiaTMP == 0)
                                {
                                    igiaTMP = int.Parse(dr["DON_GIA"] + "");
                                    drMIN = dr;
                                }
                                else if (igiaTMP > int.Parse(dr["DON_GIA"] + ""))
                                {
                                    igiaTMP = int.Parse(dr["DON_GIA"] + "");
                                    drMIN = dr;
                                }
                            }
                            dr["KM_PHANTRAM"] = 0;
                            dr["KM_TIEN"] = 0;
                        }
                        drMIN["KM_PHANTRAM"] = _iKhuyenmai_GiaTri;
                        int iDON_GIA = int.Parse(drMIN["DON_GIA"] + "");
                        float iSO_LUONG = 1;// int.Parse(drMIN["SO_LUONG"] + "");
                        Double dKM_TIEN = this.tinh_phantram(iDON_GIA * iSO_LUONG, drMIN["KM_PHANTRAM"] + "%", new Label());
                        drMIN["KM_TIEN"] = dKM_TIEN;
                        #endregion
                        //ogiamgia_theVIP = giamgia_theVIP.mon_renhat_phantram;
                    }
                    else if (_sHINHTHUC_KM == "6")
                    {
                        #region "   MonCuoiCung_Tien"
                        DataRow dr = null;
                        for (int i111 = 0; i111 < tbBH_PHIEU_CT_TMP.Rows.Count; i111++)
                        //foreach (DataRow dr111 in tbBH_PHIEU_CT_TMP.Rows)
                        {
                            tbBH_PHIEU_CT_TMP.Rows[i111]["KM_PHANTRAM"] = 0;
                            tbBH_PHIEU_CT_TMP.Rows[i111]["KM_TIEN"] = 0;
                            if (tbKhuyenMai_HangHoa.Select("MAHHBAN = '" + tbBH_PHIEU_CT_TMP.Rows[i111]["MAHH"] + "'").Length > 0)
                                dr = tbBH_PHIEU_CT_TMP.Rows[i111];
                        }
                        if (dr != null)
                        {//du lieu dong cuoi cung co MON HANG trong DS khuyen_mai
                            dr["KM_PHANTRAM"] = 0;
                            dr["KM_TIEN"] = _iKhuyenmai_GiaTri;
                        }
                        #endregion
                        //ogiamgia_theVIP = giamgia_theVIP.mon_cuoicung_tien;
                    }
                    else if (_sHINHTHUC_KM == "7")
                    {//
                        #region "   MonCuoiCung_%"
                        DataRow dr = null;
                        for (int i111 = 0; i111 < tbBH_PHIEU_CT_TMP.Rows.Count; i111++)
                        //foreach (DataRow dr111 in tbBH_PHIEU_CT_TMP.Rows)
                        {
                            tbBH_PHIEU_CT_TMP.Rows[i111]["KM_PHANTRAM"] = 0;
                            tbBH_PHIEU_CT_TMP.Rows[i111]["KM_TIEN"] = 0;
                            if (tbKhuyenMai_HangHoa.Select("MAHHBAN = '" + tbBH_PHIEU_CT_TMP.Rows[i111]["MAHH"] + "'").Length > 0)
                                dr = tbBH_PHIEU_CT_TMP.Rows[i111];
                        }
                        if (dr != null)
                        {//du lieu dong cuoi cung ma MON HANG trong DS khuyen_mai
                            //DataRow dr = tbBH_PHIEU_CT_TMP.Rows[tbBH_PHIEU_CT_TMP.Rows.Count - 1];
                            dr["KM_PHANTRAM"] = _iKhuyenmai_GiaTri;

                            int iDON_GIA = int.Parse(dr["DON_GIA"] + "");
                            float iSO_LUONG = 1;// int.Parse(dr["SO_LUONG"] + "");
                            Double dKM_TIEN = this.tinh_phantram(iDON_GIA * iSO_LUONG, dr["KM_PHANTRAM"] + "%", new Label());
                            dr["KM_TIEN"] = dKM_TIEN;
                        }
                        #endregion
                        //ogiamgia_theVIP = giamgia_theVIP.mon_cuoicung_phantram;
                    }
                    int iKM_TIEN = 0;
                    int.TryParse(tbBH_PHIEU_CT_TMP.Compute("SUM(KM_TIEN)", "") + "", out iKM_TIEN);
                    tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] = iKM_TIEN;
                    #endregion
                }
                if (_sHINHTHUC_KM == "8")
                {
                    #region "   Mua x món A tặng y món B"
                    if (_iKhuyenmai_GiaTri > 0)
                    {
                        DataTable tbQuaTang = this.Load_DM_KHUYENMAI_CT(sDM_KHUYENMAI_MA);
                        string sMaHHBAN = "";
                        string sMaHHTang = "";//iSL_qua
                        int iSLMua_DanhMuc = _iKhuyenmai_GiaTri;        //DM_KHUYENMAI.iTHAMSO_1
                        int iSLTang_DanhMuc = (int)_ithanh_tienKHUYENMAI;  //DM_KHUYENMAI.iTHAMSO_2                        

                        #region "   foreach (DataRow dr in tbQuaTang.Rows)"
                        foreach (DataRow dr in tbQuaTang.Rows)
                        {
                            sMaHHBAN = dr["MaHHBAN"] + "";
                            sMaHHTang = dr["MaHHTang"] + "";//iSL_qua
                            if (tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0").Length > 0)
                            { //neu HHBan co trong danh sach PHIEU_CT
                                //if (tbBH_PHIEU_CT_TMP.Select("MAHH = '" + sMaHHTang + "'").Length > 0)
                                { //neu HHTang co trong danh sach PHIEU_CT
                                    if (sMaHHBAN == sMaHHTang)
                                    {
                                        #region "   sMaHHBAN == sMaHHTang"
                                        DataRow[] dr1 = tbBH_PHIEU_CT_TMP.Select("MAHH = '" + sMaHHBAN + "' AND DON_GIA > 0");
                                        int iSL_duoc_khuyenmai = 0;
                                        int iSL_trenBill = 0;
                                        int iSL_TMP = 0;
                                        foreach (DataRow dr2 in dr1)
                                        {
                                            int.TryParse(dr2["SO_LUONG"] + "", out iSL_TMP);
                                            iSL_trenBill += iSL_TMP;
                                        }

                                        #region "   while (iSL_trenBill >= iSLMua_DanhMuc + iSLTang_DanhMuc)"

                                        while (iSL_trenBill >= iSLMua_DanhMuc)
                                        {//nếu SL tren BILL đủ SL of chương trình khuyến mãi
                                            iSL_duoc_khuyenmai += iSLTang_DanhMuc;
                                            iSL_trenBill -= iSLMua_DanhMuc;
                                        }
                                        #endregion

                                        #region "   if (iSL_duoc_khuyenmai > 0)"
                                        if (iSL_duoc_khuyenmai > 0)
                                        {//neu SL du de duoc KHUYEN MAI thi...update lai SL vao bang tbBH_PHIEU_CT_TMP

                                            DataRow[] drHHTang = tbBH_PHIEU_CT_TMP.Select("MAHH = '" + sMaHHTang + "' AND DON_GIA = 0");

                                            if (drHHTang.Length == 0)
                                            {//chua co dong nao duoc KM
                                                DataRow drTMP = tbBH_PHIEU_CT_TMP.NewRow();
                                                drTMP.ItemArray = dr1[0].ItemArray;
                                                //
                                                drTMP["OBJID"] = "-1";
                                                drTMP["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                drTMP["DON_GIA"] = 0;
                                                tbBH_PHIEU_CT_TMP.Rows.Add(drTMP);
                                            }
                                            else
                                            { //da ton tai DÒNG dc KM
                                                int iSL_DaKM_DUONG = 0;
                                                int iSL_DaKM_AM = 0;
                                                foreach (DataRow drTang in drHHTang)
                                                {
                                                    if (drTang["OBJID"] + "" == "-1")
                                                    {
                                                        iSL_DaKM_AM += int.Parse(drTang["SO_LUONG"] + "");
                                                    }
                                                    else
                                                        iSL_DaKM_DUONG += int.Parse(drTang["SO_LUONG"] + "");
                                                }


                                                #region "   if (iSL_DaKM_DUONG > 0)"
                                                iSL_duoc_khuyenmai = iSL_duoc_khuyenmai - iSL_DaKM_DUONG;
                                                if (iSL_duoc_khuyenmai == 0)
                                                {//so luong KM_DUONG vua du
                                                    foreach (DataRow drTang in drHHTang)
                                                    {
                                                        if (drTang["OBJID"] + "" == "-1")
                                                        {
                                                            tbBH_PHIEU_CT_TMP.Rows.Remove(drTang);
                                                            iSL_duoc_khuyenmai = 0;
                                                        }
                                                    }
                                                    return;
                                                }
                                                else
                                                {
                                                    if (iSL_DaKM_AM > 0)
                                                    {//UPDATE
                                                        foreach (DataRow drTang in drHHTang)
                                                        {
                                                            if (drTang["OBJID"] + "" == "-1")
                                                            {
                                                                drTang["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                                iSL_duoc_khuyenmai = 0;
                                                                return;
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {//INSERT
                                                        DataRow drTMP = tbBH_PHIEU_CT_TMP.NewRow();
                                                        drTMP.ItemArray = dr1[0].ItemArray;
                                                        //
                                                        drTMP["OBJID"] = "-1";
                                                        drTMP["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                        drTMP["DON_GIA"] = 0;
                                                        tbBH_PHIEU_CT_TMP.Rows.Add(drTMP);
                                                    }
                                                }
                                                #endregion



                                                //foreach (DataRow drTang in drHHTang)
                                                //    if (drTang["OBJID"] + "" == "-1")
                                                //    {
                                                //        drTang["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                //        return;
                                                //    }
                                                //if (iSL_duoc_khuyenmai > 0)
                                                //{
                                                //    #region "   INSERT"
                                                //    DataRow drTMP = tbBH_PHIEU_CT_TMP.NewRow();
                                                //    drTMP.ItemArray = dr1[0].ItemArray;
                                                //    drTMP["OBJID"] = "-1";
                                                //    drTMP["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                //    drTMP["DON_GIA"] = 0;
                                                //    tbBH_PHIEU_CT_TMP.Rows.Add(drTMP);
                                                //    #endregion
                                                //}
                                                //else if (iSL_duoc_khuyenmai < 0)
                                                //{ 

                                                //}

                                            }
                                        }
                                        else
                                        {
                                            DataRow[] drHHTang1 = tbBH_PHIEU_CT_TMP.Select("OBJID = -1 AND MAHH = '" + sMaHHTang + "' AND DON_GIA = 0");
                                            foreach (DataRow drTMP in drHHTang1)
                                                tbBH_PHIEU_CT_TMP.Rows.Remove(drTMP);

                                            DataRow[] drHHTang2 = tbBH_PHIEU_CT_TMP.Select("OBJID > 0 AND MAHH = '" + sMaHHTang + "' AND DON_GIA = 0");
                                            foreach (DataRow drTMP in drHHTang2)
                                            {
                                                #region "   INSERT"
                                                int.TryParse(drTMP["SO_LUONG"] + "", out iSL_duoc_khuyenmai);

                                                DataRow drTMP1 = tbBH_PHIEU_CT_TMP.NewRow();
                                                drTMP1.ItemArray = dr1[0].ItemArray;
                                                drTMP1["OBJID"] = "-1";
                                                drTMP1["SO_LUONG"] = iSL_duoc_khuyenmai * -1;
                                                drTMP1["DON_GIA"] = 0;
                                                tbBH_PHIEU_CT_TMP.Rows.Add(drTMP1);
                                                #endregion
                                            }
                                        }
                                        #endregion

                                        #endregion
                                    }
                                    else
                                    {
                                        #region "   sMaHHBAN != sMaHHTang"
                                        //DataRow drHHBAN = tbBH_PHIEU_CT_TMP.Select("MAHH = '" + sMaHHBAN + "' AND DON_GIA > 0")[0];
                                        DataRow[] drHHTang = tbBH_PHIEU_CT_TMP.Select("MAHH = '" + sMaHHTang + "'");

                                        if (drHHTang.Length == 0)
                                        {
                                            #region "   chua co HH tang ton tai trong Phieu_CT"
                                            DataTable tbDM_HH = new thuvien().SP_SelectDataTable("sp_mh_banhang",
                                                                                                new string[] { "@flag", "@OBJID" },
                                                                                                new object[] { 22, sMaHHTang });
                                            if (tbDM_HH.Rows.Count > 0)
                                            {
                                                DataRow drh = tbDM_HH.Rows[0];
                                                this.Insert2TableCT(drh["NHOMCHUHH_CODE"] + "",
                                                                    drh["ma_HH"] + "",
                                                                    drh["ten_HH"] + "",
                                                                    0,//float.Parse("0" + drh["GIA1"]),//KHUYEN_MAI ==> GIA = 0.
                                                                    1,
                                                                    drh["Ma_DVT"] + "",
                                                                    0,
                                                                    drh["DM_MAYIN_BEP_MA"] + "", drh["VAT_PHANTRAM"] + "");

                                            }
                                            #endregion
                                        }

                                        drHHTang = tbBH_PHIEU_CT_TMP.Select("MAHH = '" + sMaHHTang + "'");
                                        if (drHHTang.Length > 0)
                                        {
                                            #region "   da co HH tang"
                                            int iSL_trenBill = 0;
                                            int.TryParse(tbBH_PHIEU_CT_TMP.Compute("SUM(SO_LUONG)", "DON_GIA > 0 AND MAHH LIKE '" + sMaHHBAN + "'") + "", out iSL_trenBill);



                                            int iSL_KO_duoc_khuyenmai = 0;
                                            int iSL_duoc_khuyenmai = 0;

                                            int iSL_datang_trenBILL = 0;
                                            int iSL_datang_trenBILL_Duong = 0;
                                            foreach (DataRow drTMP in drHHTang)
                                            {
                                                int iTMP = 0;
                                                int.TryParse(drTMP["SO_LUONG"] + "", out iTMP);
                                                iSL_datang_trenBILL += iTMP;

                                                if (drTMP["OBJID"] + "" != "-1")//HH da tặng trên BILL, SL < 0
                                                    iSL_datang_trenBILL_Duong += iTMP;//HH da tặng trên BILL, SL > 0
                                            }
                                            //      
                                            #region "   while (iSL_trenBill >= iSLMua_DanhMuc)"
                                            while (iSL_trenBill >= iSLMua_DanhMuc)
                                            {
                                                iSL_duoc_khuyenmai += iSLTang_DanhMuc;
                                                iSL_trenBill -= iSLMua_DanhMuc;
                                            }
                                            #endregion

                                            #region "   if (iSL_duoc_khuyenmai > 0)"
                                            if (iSL_duoc_khuyenmai > 0)
                                            {
                                                //neu so luong duoc KM(trong DM KhuyenMai) >= so luong of sp KM(trong BILL),
                                                //thi tat ca sp KM(trong BILL) don_gia deu = 0
                                                if (iSL_duoc_khuyenmai > iSL_datang_trenBILL)
                                                {
                                                    #region
                                                    DataRow[] drHH_TMP = tbBH_PHIEU_CT_TMP.Select("OBJID = -1 AND MAHH = '" + sMaHHTang + "' AND DON_GIA = 0");
                                                    iSL_duoc_khuyenmai = iSL_duoc_khuyenmai - iSL_datang_trenBILL_Duong;
                                                    if (iSL_duoc_khuyenmai == 0)
                                                    { //xoa 
                                                        foreach (DataRow dr2012 in drHH_TMP)
                                                            tbBH_PHIEU_CT_TMP.Rows.Remove(dr2012);
                                                    }
                                                    else
                                                    {
                                                        if (drHH_TMP.Length > 0)
                                                        {
                                                            drHH_TMP[0]["DON_GIA"] = 0;
                                                            drHH_TMP[0]["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                            //xoa di nhung dong KM khi SL GIAM
                                                            for (int i2012 = 1; i2012 < drHH_TMP.Length; i2012++)
                                                                tbBH_PHIEU_CT_TMP.Rows.Remove(drHH_TMP[i2012]);
                                                        }
                                                        else
                                                        {
                                                            DataRow drTMP = tbBH_PHIEU_CT_TMP.NewRow();
                                                            drTMP.ItemArray = drHHTang[0].ItemArray;
                                                            ///
                                                            drTMP["OBJID"] = "-1";
                                                            drTMP["DON_GIA"] = 0;
                                                            drTMP["COLOR"] = 2;
                                                            drTMP["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                            tbBH_PHIEU_CT_TMP.Rows.Add(drTMP);
                                                            //
                                                            //drHHTang[0]["SO_LUONG"] = iSL_KO_duoc_khuyenmai;
                                                        }
                                                    }
                                                    #endregion
                                                }
                                                else if (iSL_duoc_khuyenmai < iSL_datang_trenBILL)
                                                {
                                                    #region
                                                    //neu so luong duoc KM(trong DM KhuyenMai) < so luong of sp KM(trong BILL),
                                                    //thi so luong of sp KM(trong BILL) chia ra lam 2 dong: 1 dong co KM, 1 dong ko co KM.
                                                    DataRow[] drHH_TMP = tbBH_PHIEU_CT_TMP.Select("OBJID = -1 AND MAHH = '" + sMaHHTang + "' AND DON_GIA = 0");
                                                    iSL_duoc_khuyenmai = iSL_duoc_khuyenmai - iSL_datang_trenBILL_Duong;
                                                    if (drHH_TMP.Length > 0)
                                                    {
                                                        drHH_TMP[0]["DON_GIA"] = 0;
                                                        drHH_TMP[0]["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                        if (iSL_duoc_khuyenmai == 0)
                                                            tbBH_PHIEU_CT_TMP.Rows.Remove(drHH_TMP[0]);

                                                        //xoa di nhung dong KM khi SL GIAM
                                                        for (int i2012 = 1; i2012 < drHH_TMP.Length; i2012++)
                                                            tbBH_PHIEU_CT_TMP.Rows.Remove(drHH_TMP[i2012]);
                                                    }
                                                    else
                                                    {
                                                        iSL_KO_duoc_khuyenmai = iSL_datang_trenBILL - iSL_duoc_khuyenmai;
                                                        ///
                                                        DataRow drTMP = tbBH_PHIEU_CT_TMP.NewRow();
                                                        drTMP.ItemArray = drHHTang[0].ItemArray;
                                                        ///
                                                        drTMP["OBJID"] = "-1";
                                                        drTMP["DON_GIA"] = 0;
                                                        drTMP["COLOR"] = 2;
                                                        drTMP["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                        tbBH_PHIEU_CT_TMP.Rows.Add(drTMP);
                                                        //
                                                        drHHTang[0]["SO_LUONG"] = iSL_KO_duoc_khuyenmai;
                                                    }
                                                    #endregion
                                                }
                                                else
                                                {

                                                }
                                            }
                                            else
                                            {
                                                iSL_duoc_khuyenmai = 0;
                                                foreach (DataRow drTMP in tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHTang + "' AND DON_GIA = 0"))
                                                {
                                                    if (drTMP["OBJID"] + "" == "-1")//neu chua TAM TINH thi ==> XOA
                                                        tbBH_PHIEU_CT_TMP.Rows.Remove(drTMP);
                                                    else//NEU DA tam tinh oy thi ==> them SL ÂM, de tru ra khi luu
                                                        iSL_duoc_khuyenmai += int.Parse(drTMP["SO_LUONG"] + "");
                                                }

                                                if (iSL_duoc_khuyenmai > 0)
                                                {//NEU DA tam tinh oy thi ==> them SL ÂM, de tru ra khi luu
                                                    DataRow drTMP = tbBH_PHIEU_CT_TMP.NewRow();
                                                    drTMP.ItemArray = tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHTang + "'")[0].ItemArray;
                                                    //
                                                    drTMP["OBJID"] = "-1";
                                                    drTMP["SO_LUONG"] = iSL_duoc_khuyenmai;
                                                    drTMP["DON_GIA"] = 0;
                                                    drTMP["COLOR"] = 2;
                                                    tbBH_PHIEU_CT_TMP.Rows.Add(drTMP);
                                                }
                                            }
                                            #endregion
                                            #endregion
                                        }

                                        #endregion
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    #endregion
                }
                else if (_sHINHTHUC_KM == "9")
                {
                    #region "   Mua x món A giảm y tiền"
                    int iKhuyenMaiSL_Mua = 0;
                    int iKhuyenMaiTien_Tang = 0;
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_1"] + "", out iKhuyenMaiSL_Mua);
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_2"] + "", out iKhuyenMaiTien_Tang);
                    //
                    int iPHIEU_CT_SL_Mua = 0;
                    //
                    int iKM_TIEN = 0;
                    //
                    _sHINHTHUC_KM = _sHINHTHUC_KM + "";
                    DataTable tbQuaTang = this.Load_DM_KHUYENMAI_CT(sDM_KHUYENMAI_MA);
                    string sMaHHBAN = "";

                    #region "   foreach (DataRow dr in tbQuaTang.Rows)"
                    foreach (DataRow dr in tbQuaTang.Rows)
                    {
                        sMaHHBAN = dr["MaHHBAN"] + "";

                        if (tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0 AND SO_LUONG >= " + iKhuyenMaiSL_Mua).Length > 0)
                        { //neu HHBan co trong danh sach PHIEU_CT                            
                            int.TryParse(tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0")[0]["SO_LUONG"] + "", out iPHIEU_CT_SL_Mua);
                            iKM_TIEN = (iPHIEU_CT_SL_Mua / iKhuyenMaiSL_Mua) * iKhuyenMaiTien_Tang;
                            //phai ghi chu la KM mon nao??????????
                            tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0")[0]["KM_TIEN"] = iKM_TIEN;
                        }
                    }
                    int.TryParse(tbBH_PHIEU_CT_TMP.Compute("SUM(KM_TIEN)", "") + "", out iKM_TIEN);
                    tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] = iKM_TIEN;
                    #endregion

                    #endregion
                }
                else if (_sHINHTHUC_KM == "10")
                {
                    #region "   Mua x món A giảm y% tiền"
                    int iKhuyenMaiSL_Mua = 0;
                    int iKhuyenMaiTien_PhanTram = 0;    //% tien
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_1"] + "", out iKhuyenMaiSL_Mua);
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_2"] + "", out iKhuyenMaiTien_PhanTram);    //% tien
                    //
                    int iPHIEU_CT_SL_Mua = 0;
                    //
                    double iKM_TIEN = 0;
                    //
                    _sHINHTHUC_KM = _sHINHTHUC_KM + "";
                    DataTable tbQuaTang = this.Load_DM_KHUYENMAI_CT(sDM_KHUYENMAI_MA);
                    string sMaHHBAN = "";
                    double iDonGia = 0;
                    #region "   foreach (DataRow dr in tbQuaTang.Rows)"
                    foreach (DataRow dr in tbQuaTang.Rows)
                    {
                        sMaHHBAN = dr["MaHHBAN"] + "";

                        int.TryParse(tbBH_PHIEU_CT_TMP.Compute("SUM(SO_LUONG)", "MAHH LIKE '" + sMaHHBAN + "'") + "", out iPHIEU_CT_SL_Mua);

                        if (iPHIEU_CT_SL_Mua >= iKhuyenMaiSL_Mua)
                        { //neu HHBan co trong danh sach PHIEU_CT                            



                            //int.TryParse(tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0 AND SO_LUONG >= " + iKhuyenMaiSL_Mua)[0]["SO_LUONG"] + "", out iPHIEU_CT_SL_Mua);
                            double.TryParse(tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0 ")[0]["DON_GIA"] + "", out iDonGia);

                            //3-->  10% (n)
                            //7--> 2*10% (n)                            
                            iDonGia = (iPHIEU_CT_SL_Mua / iKhuyenMaiSL_Mua) * iKhuyenMaiSL_Mua * iDonGia;//SL duoc khuyen mai * Don_Gia

                            iKM_TIEN = this.tinh_phantram(iDonGia, iKhuyenMaiTien_PhanTram + "%", new Label());

                            tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0 ")[0]["KM_PHANTRAM"] = iKhuyenMaiTien_PhanTram;
                            tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHBAN + "' AND DON_GIA > 0 ")[0]["KM_TIEN"] = iKM_TIEN;
                        }
                    }
                    double.TryParse(tbBH_PHIEU_CT_TMP.Compute("SUM(KM_TIEN)", "") + "", out iKM_TIEN);
                    tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] = iKM_TIEN;
                    #endregion

                    #endregion
                }
            }
            else if (tbBH_PHIEU_TMP.Rows[0]["DM_KHUYENMAI_MA"] + "" != "-1" && tbBH_PHIEU_TMP.Rows[0]["DM_KHUYENMAI_MA"] + "" != "")
            {
                #region "   khuyen mai DIEM"
                string sSQL = "SELECT ISNULL((SELECT SUM(DIEM) FROM BH_PHIEU_LUU_DIEM WHERE DM_THE_CODE LIKE '" + sMaThe_VIP + "'), 0) " +
                                "- ISNULL((SELECT SUM(DIEM) FROM BH_PHIEU_DOIDIEM_THANHMON WHERE DM_THE_CODE LIKE '" + sMaThe_VIP + "' AND OBJID NOT LIKE '" + tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "'),0)";
                int idiemHienCo = 0;
                DataTable tbDIEM = new thuvien().SP_SelectDataTable("SP_EXECUTESQL",
                                                                new string[] { "@sSQL" },
                                                                new object[] { sSQL });

                if (tbDIEM.Rows.Count > 0)
                    int.TryParse(tbDIEM.Rows[0][0] + "", out idiemHienCo);

                if (_sHINHTHUC_KM == "11")
                {
                    #region "   Đạt x điểm tặng y tiền"
                    _sHINHTHUC_KM = _sHINHTHUC_KM + "";
                    int iDiemDanhMucKM = 0;
                    int itien_thuong = 0;
                    int iDiem_da_tru = 0;
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_1"] + "", out iDiemDanhMucKM);
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_2"] + "", out itien_thuong);
                    //
                    tbBH_PHIEU_TMP.Rows[0]["KM_PHANTRAM"] = 0;
                    if (idiemHienCo >= iDiemDanhMucKM)
                    {
                        object oTONG_TIEN = tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"];
                        object oKM_TIEN = tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"];
                        iDiem_da_tru = idiemHienCo / iDiemDanhMucKM * iDiemDanhMucKM;

                        tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] = itien_thuong * (idiemHienCo / iDiemDanhMucKM);
                    }
                    else//ko du DIEM de duoc khuyen mai
                        tbBH_PHIEU_TMP.Rows[0]["KM_TIEN"] = 0;

                    ///
                    ///iDiem_da_tru
                    ///
                    #region "   Luu diem vao BH_PHIEU_DOIDIEM_THANHMON"
                    if (iDiem_da_tru > 0)
                    {
                        //
                        //
                        //
                        //
                        new thuvien().SP_Update("sp_BH_PHIEU_DOIDIEM_THANHMON",
                                                new string[] { "@flag", "@DIEM", "@DM_THE_CODE", 
                                                                            "@GHI_CHU", "@OBJID" },
                                                new object[] { 1, iDiem_da_tru, sMaThe_VIP, 
                                                                            "Tổng điểm trước: "+(idiemHienCo+iDiem_da_tru),tbBH_PHIEU_TMP.Rows[0]["OBJID"] });
                    }
                    #endregion
                    #endregion
                }
                else if (_sHINHTHUC_KM == "12")
                {//tang QUÀ, MẶT HÀNG. chỉ 1 món HH duy nhất
                    #region "   Đạt x điểm tặng y quà"
                    _sHINHTHUC_KM = _sHINHTHUC_KM + "";
                    int iDiemDanhMucKM = 0;
                    int iSL_quaTang = 0;//số lượng quà tặng
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_1"] + "", out iDiemDanhMucKM);
                    int.TryParse(tbKhuyenMai_HangHoa.Rows[0]["THAMSO_2"] + "", out iSL_quaTang);
                    //chi nhan 1 mon qua, nhung SL = 1 or Nhieu

                    if (idiemHienCo >= iDiemDanhMucKM)
                    {
                        DataTable tbQuaTang = this.Load_DM_KHUYENMAI_CT(sDM_KHUYENMAI_MA);
                        if (tbQuaTang.Rows.Count > 0 && idiemHienCo >= iDiemDanhMucKM)
                        {//chi tang 1 món HH duy nhat(co the SL = 1 or > 1).
                            //string sMaHHBAN = tbQuaTang.Rows[0]["MaHHBAN"] + "";
                            //string sMaQUATang = tbQuaTang.Rows[0]["MaQUATang"] + "";

                            string sMaHHTang = tbQuaTang.Rows[0]["MaHHTang"] + "";//iSL_qua

                            if (sMaHHTang != "")//tang HANG_HOA
                            {
                                int iDiem_da_tru = 0;
                                int iSL_da_tru = 0;
                                //
                                int iSL_trenBill = 0;

                                DataRow[] drs_HHTang = tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHTang + "'");
                                if (drs_HHTang.Length > 0)
                                {//neu co HH_KhuyenMai trong Phieu_CT
                                    //int.TryParse(drs_HHTang[0]["SO_LUONG"] + "", out iSL_trenBill);                                                                        
                                    int.TryParse(tbBH_PHIEU_CT_TMP.Compute("SUM(SO_LUONG)", "MAHH LIKE '" + sMaHHTang + "'") + "", out iSL_trenBill);

                                    #region "   while - Tru di SL KM"
                                    while (idiemHienCo >= iDiemDanhMucKM //neu DIEM HIEN CO >= DIEM KHUYEN MAI
                                        && iSL_trenBill >= iSL_quaTang)//neu con SL MON HANG
                                    {
                                        iDiem_da_tru += iDiemDanhMucKM; //Diem_da_tru
                                        iSL_da_tru += iSL_quaTang;      //SL_da_tru
                                        idiemHienCo -= iDiemDanhMucKM;
                                        iSL_trenBill -= iSL_quaTang;
                                    }
                                    #endregion
                                    //
                                    if (iDiem_da_tru > 0 && iSL_da_tru > 0)//neu co duyet qua vong lap WHILE
                                    {
                                        DataRow[] drs_HHTang_DON_GIA_0 = tbBH_PHIEU_CT_TMP.Select("MAHH LIKE '" + sMaHHTang + "' AND DON_GIA = 0");

                                        #region "   drs_HHTang_DON_GIA_0[]"
                                        if (drs_HHTang_DON_GIA_0.Length > 0)
                                        {//neu da co SO LUONG KHUYEN MAI mat hang đó ton tai trong BILL             
                                            //drs_HHTang_DON_GIA_0[""] = iDiem_da_tru;                                            
                                            if (iSL_da_tru == 0)
                                                tbBH_PHIEU_CT_TMP.Rows.Remove(drs_HHTang_DON_GIA_0[0]);
                                            else
                                                drs_HHTang_DON_GIA_0[0]["SO_LUONG"] = iSL_da_tru;
                                        }
                                        else if (iSL_da_tru > 0)
                                        {//neu chua co SO LUONG KHUYEN MAI nào của mat hang đó ton tai trong BILL   
                                            DataRow drTMP = tbBH_PHIEU_CT_TMP.NewRow();
                                            drTMP.ItemArray = drs_HHTang[0].ItemArray;
                                            drTMP["OBJID"] = -1;
                                            drTMP["DON_GIA"] = 0;
                                            drTMP["SO_LUONG"] = iSL_da_tru;
                                            tbBH_PHIEU_CT_TMP.Rows.Add(drTMP);
                                        }
                                        #endregion

                                        #region "   drs_HHTang[]"
                                        if (iSL_trenBill > 0)
                                            drs_HHTang[0]["SO_LUONG"] = iSL_trenBill;
                                        else
                                            tbBH_PHIEU_CT_TMP.Rows.Remove(drs_HHTang[0]);
                                        #endregion

                                        grdBH_PHIEU.Refresh();
                                    }
                                }

                                ///
                                ///iDiem_da_tru
                                ///
                                #region "   Luu diem vao BH_PHIEU_DOIDIEM_THANHMON"
                                if (iDiem_da_tru > 0)
                                {
                                    //
                                    //
                                    //
                                    //
                                    new thuvien().SP_Update("sp_BH_PHIEU_DOIDIEM_THANHMON",
                                                            new string[] { "@flag", "@DIEM", "@DM_THE_CODE", 
                                                                            "@GHI_CHU", "@OBJID" },
                                                            new object[] { 1, iDiem_da_tru, sMaThe_VIP, 
                                                                            "Tổng điểm trước: "+(idiemHienCo+iDiem_da_tru),tbBH_PHIEU_TMP.Rows[0]["OBJID"] });
                                }
                                #endregion
                            }
                        }
                    }
                    #endregion
                }
                #endregion
            }
        }

        DataTable Load_DM_KHUYENMAI_CT(string _sDM_KHUYENMAI_MA)
        {
            string sSQL = "SELECT * FROM DM_KHUYENMAI_CT WHERE MAKM LIKE '" + _sDM_KHUYENMAI_MA + "'";
            DataTable _tbQuaTang = new thuvien().SP_SelectDataTable("SP_EXECUTESQL",
                                                                    new string[] { "@sSQL" },
                                                                    new object[] { sSQL });
            return _tbQuaTang;
        }
        #endregion

        #region "   lblGiaBan_Click"
        private void lblGiaBan_Click(object sender, EventArgs e)
        {
            if (ochon == chon.GiaBan)
                ochon = chon.None;
            else

                ochon = chon.GiaBan;

        }
        #endregion

        #region "   lblPHU_THU_KHAC_Click"
        private void lblPHU_THU_KHAC_Click(object sender, EventArgs e)
        {
            mh_so_Ban_Gia_Mo omh_so_Ban_Gia_Mo = new mh_so_Ban_Gia_Mo("Phụ thu khác", tbBH_PHIEU_TMP.Rows[0]["PHU_THU_KHAC"] + "", "-");
            object igiatri = omh_so_Ban_Gia_Mo.ShowForm();
            if (omh_so_Ban_Gia_Mo.DialogResult == DialogResult.OK)
            {
                int iso = 0;
                int.TryParse(igiatri + "", out iso);
                lblHD_Phu_Thu_Khac.Text = iso.ToString("N0");
                tbBH_PHIEU_TMP.Rows[0]["PHU_THU_KHAC"] = iso;
            }
        }
        #endregion

        #region "   Reset_pnlSoDo_MonAn"
        void Reset_pnlSoDo_MonAn()
        {
            this.splitContainerControl2.Panel2.Controls.Remove(this.pnlSoDo_MonAn);
            this.pnlSoDo_MonAn = new System.Windows.Forms.Panel();
            this.pnlSoDo_MonAn.AutoScroll = true;
            this.pnlSoDo_MonAn.BackColor = System.Drawing.Color.White;
            this.pnlSoDo_MonAn.BackgroundImage = global::LPV_POS.Properties.Resources.back_banhang;
            this.pnlSoDo_MonAn.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pnlSoDo_MonAn.Location = new System.Drawing.Point(0, 0);
            this.pnlSoDo_MonAn.Name = "pnlSoDo_MonAn";
            this.pnlSoDo_MonAn.Size = new System.Drawing.Size(581, 605);
            this.pnlSoDo_MonAn.TabIndex = 14;
            this.splitContainerControl2.Panel2.Controls.Add(this.pnlSoDo_MonAn);
        }
        #endregion

        #region "   GetDAT_COC"
        float GetDAT_COC(string _sBH_Phieu_Ma)
        {
            float iDAT_COC = 0;
            try
            {
                string sSQL = "SELECT DB.DAT_COC FROM DM_BAN_DAT_BAN DB WHERE DB.BH_PHIEU_ID LIKE '" + _sBH_Phieu_Ma + "'";
                DataTable tbDatCoc = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });
                if (tbDatCoc.Rows.Count > 0)
                    float.TryParse(tbDatCoc.Rows[0]["DAT_COC"] + "", out iDAT_COC);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            return iDAT_COC;
        }
        #endregion

        #region "   Tinh tiền giờ"
        #region "   Tinh_Tien_Gio_Click"
        void Tinh_Tien_Gio_Click()
        {
            //if (tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "" == "" || tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "" == "-1")
            //{
            //    //new mh_thongbao("Cập nhật bán hàng trước khi tính tiền.", 2).ShowDialog();
            //    //return;
            //    tbBH_PHIEU_TMP.Rows[0]["OBJID"] = " ";
            //    this.Luu_TamTinh();
            //}

            object nNgayGioVao = this.GetGioVao(false);
            object nNgayGioRa = timer1.Tag;

            float iGio = this.TinhGio((DateTime)nNgayGioVao, (DateTime)nNgayGioRa, lblCoTinhGio_TheoNgay.Tag + "" == "1");

            if (tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'").Length > 0)
            {//da tontai --> Update
                DataRow drTienGio = tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'")[tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'").Length - 1];//
                drTienGio["NGAY_TINH_GIO"] = nNgayGioRa;
                drTienGio["SO_LUONG"] = 1;

                string _maphieu = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
                double dTHANH_TIEN = this.LoadTienGio((DateTime)nNgayGioVao, _maphieu, (DateTime)drTienGio["NGAY_TINH_GIO"], sBAN_MA);
                //drTienGio["THANH_TIEN"] = dTHANH_TIEN;
                //drTienGio["THANH_TIEN_TRUOC"] = dTHANH_TIEN;
                drTienGio["DON_GIA"] = dTHANH_TIEN;
            }
            else
            {//ko ton tai -- Insert
                DataRow drTienGio = null;
                drTienGio = tbBH_PHIEU_CT_TMP.NewRow();
                drTienGio["NGAY_TINH_GIO"] = nNgayGioRa;
                drTienGio["MAHH"] = "Tien_Gio";
                drTienGio["OBJNAME_HH_root"] = "Tiền giờ";
                drTienGio["OBJNAME_HH"] = "Tiền giờ";
                drTienGio["SO_LUONG"] = 1;

                string _maphieu = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
                double dTHANH_TIEN = this.LoadTienGio((DateTime)nNgayGioVao, _maphieu, (DateTime)drTienGio["NGAY_TINH_GIO"], sBAN_MA);
                drTienGio["THANH_TIEN"] = dTHANH_TIEN;
                //drTienGio["THANH_TIEN_TRUOC"] = dTHANH_TIEN;

                drTienGio["DON_GIA"] = dTHANH_TIEN;// Math.Round(dTHANH_TIEN / iGio, 0);

                tbBH_PHIEU_CT_TMP.Rows.Add(drTienGio);
                ihandle = tbBH_PHIEU_CT_TMP.Rows.Count - 1;
            }
        }
        #endregion

        #region "   CatCo_Click"
        private void CatCo_Click()
        {
            Boolean bCAT_THOIGIAN = false;
            if (tbDM_LOAIDICHVU.Rows.Count > 0)
                if (tbDM_LOAIDICHVU.Rows[0]["CAT_THOIGIAN"] + "" != "")
                    bCAT_THOIGIAN = (Boolean)tbDM_LOAIDICHVU.Rows[0]["CAT_THOIGIAN"];

            object nNgayGioVao = this.GetGioVao(bCAT_THOIGIAN);
            object nNgayGioRa = timer1.Tag;

            // -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -== -==

            float iGio = this.TinhGio((DateTime)nNgayGioVao, (DateTime)nNgayGioRa, lblCoTinhGio_TheoNgay.Tag + "" == "1");

            if (bCAT_THOIGIAN)
            {//chua tontai --> AddNew
                //hoac da ton_tai, ma co CAT_GIO
                DataRow drTienGio = null;
                drTienGio = tbBH_PHIEU_CT_TMP.NewRow();
                drTienGio["NGAY_TINH_GIO"] = nNgayGioRa;
                drTienGio["MAHH"] = "Tien_Gio";
                drTienGio["OBJNAME_HH_root"] = "Tiền giờ";
                drTienGio["OBJNAME_HH"] = "Tiền giờ";
                drTienGio["SO_LUONG"] = 1;

                string _maphieu = tbBH_PHIEU_TMP.Rows[0]["OBJID"] + "";
                double dTHANH_TIEN = this.LoadTienGio((DateTime)nNgayGioVao, _maphieu, (DateTime)drTienGio["NGAY_TINH_GIO"], sBAN_MA);
                drTienGio["THANH_TIEN"] = dTHANH_TIEN;
                //drTienGio["THANH_TIEN_TRUOC"] = dTHANH_TIEN;

                drTienGio["DON_GIA"] = dTHANH_TIEN;// Math.Round(dTHANH_TIEN / iGio, 0);

                tbBH_PHIEU_CT_TMP.Rows.Add(drTienGio);
                ihandle = tbBH_PHIEU_CT_TMP.Rows.Count - 1;
            }
        }
        #endregion

        #region "   lblTinh_TienGio_Click"
        private void lblCatCo_Click(object sender, EventArgs e)
        {
            #region "   Cat Co - bo"
            ////Buoc 1. tinh tien giờ dòng Tien_Gio hien hành
            ////Buoc 2. Them 1 dong Tien_Gio moi 
            //ochon = chon.None;
            //if (lblCatCo.Text != "")
            //{
            //    //1.
            //    this.Tinh_Tien_Gio_Click();
            //    //2.
            //    this.CatCo_Click();

            //    this.TinhTongSUM();
            //}
            #endregion


            string sSQL = "";

            if (Variable.tbBH_CAU_HINH.Rows.Count > 0)
            {//TI_GIA_USD
                int iTI_GIA_USD = 0;
                int.TryParse(Variable.tbBH_CAU_HINH.Rows[0]["TI_GIA_USD"] + "", out iTI_GIA_USD);
                mh_so omh_so = new mh_so("Tỷ giá USD", iTI_GIA_USD, "Lưu");
                iTI_GIA_USD = omh_so.ShowForm();
                if (omh_so.DialogResult == DialogResult.OK)
                { //SAVE
                    sSQL = "UPDATE BH_CAU_HINH SET TI_GIA_USD = " + iTI_GIA_USD;
                    int i = new thuvien().SP_Update("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });
                    new cpublic().Load_tbBH_CAU_HINH();
                }
            }
            else
            {
                MessageBox_LPV.Show("Chưa có DỮ LIỆU trong TABLE 'BH_CAU_HINH'");
            }
        }
        #endregion

        #region "   GetGioVao"
        object GetGioVao(Boolean _bCAT_THOIGIAN)
        {
            object o1 = null;
            if (_bCAT_THOIGIAN)
                foreach (DataRow dr in tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'"))
                {
                    if (o1 != null)
                    { //SET o1 = MAX(NGAY_TINH_GIO)
                        if ((DateTime)o1 < (DateTime)dr["NGAY_TINH_GIO"])
                            o1 = dr["NGAY_TINH_GIO"];
                    }
                    else
                        o1 = dr["NGAY_TINH_GIO"];
                }
            if (o1 == null)
                o1 = tbBH_PHIEU_TMP.Rows[0]["NGAY_GIO_VAO"];

            return o1;
        }
        #endregion

        #region "   LoadTienGio"
        double LoadTienGio(DateTime _NGAY_GIO_VAO, string _MaPhieu, DateTime _NGAY_GIO_RA, string _DM_BAN_MA)
        {//hàm tính tiền giờ
            double _tiengio = 0;
            Boolean _tinhgio_theongay = (lblCoTinhGio_TheoNgay.Tag + "" == "1");
            //_NGAY_GIO_RA=_NGAY_GIO_RA.AddHours(1);
            DataTable tbTienGio = new thuvien().SP_SelectDataTable("sp_mh_banhang_sua",
                                                                    new string[] { "@flag", "@NGAY_GIO_VAO", "@OBJID", 
                                                                                   "@NGAY_GIO_RA", "@DM_BAN_MA", "@tinhgio_theongay" },
                                                                    new object[] { 11, _NGAY_GIO_VAO, _MaPhieu, 
                                                                                   _NGAY_GIO_RA, _DM_BAN_MA, _tinhgio_theongay });
            if (tbTienGio.Rows.Count > 0)
                double.TryParse(tbTienGio.Rows[0][0] + "", out _tiengio);
            _tiengio = Math.Round(_tiengio / 100.0, 0) * 100.0;
            return _tiengio;
        }
        #endregion

        #region "   TinhGio"
        float TinhGio(DateTime _giovao, DateTime _giora, Boolean _tinhgio_theongay)
        {
            float _TinhGio = 0;
            TimeSpan ts = _giora.Subtract(_giovao);
            if (_tinhgio_theongay)
            {
                _TinhGio = ts.Days + ts.Hours / 100f;
            }
            else
            {
                _TinhGio = ts.Hours + ts.Minutes / 100f;
            }
            return _TinhGio;
        }
        #endregion

        private void radio_inbillkhachhang_CheckedChanged(object sender, EventArgs e)
        {

        }


        #endregion

    }
}